c - 初始化字符串并将其传递给函数
问题描述
在这段代码中,我尝试初始化三个字符串并将其传递给一个函数:action_type; 系统类型; 房间(COLD、HOT 和 EMP 分别表示冷却系统、加热系统和员工房间)。代码代码运行但它不打印字符串。为了可视化字符串,我该怎么做?谢谢大家。
enter code here
#include <stdio.h>
#include <string.h>
#define T_MAX_EMP 25
#define T_MIN_EMP 15
#define ON 1
#define OFF 0
void SystemAction(char* action_type, char* system_type, char* room, bool power)
{
if(power == OFF)
{
printf ("%s %s %s \n", action_type, system_type, room);
power = ON;
}
else
{
if(power == ON)
{
printf("%s is still on \n", system_type);
}
}
}
void SystemCheck(int n, int system)
{
if(n == 1)
{
printf ("The heating / cooling system works correctly \n");
}
else
{
if(n == 0)
{
printf("System malfunctions have been reported \n");
system = n;
}
else
{
printf ("\n Value entered is incorrect \n");
}
}
}
int main()
{
int n;
int system = 1;
int ch;
int power = OFF;
char c;
char action_type[10];
char system_type[10];
char room[10];
do
{
printf("Enter the character and the integer: \n");
scanf (" %c %d" , &c, &n);
switch(c)
{
case 'e' :
if(system == 0)
{
printf("The system doesn't work \n");
}
else
{
if (n > T_MAX_EMP)
{
action_type[10] = "ON";
system_type[10] = "COLD";
room[10] = "EMP";
SystemAction(action_type, system_type, room, power);
}
else
{
if(n < T_MIN_EMP)
{
action_type[10] = "ON";
system_type[10] = "HOT";
room[10] = "EMP";
SystemAction(action_type, system_type, room, power);
}
}
break;
}
case 's' :
SystemCheck(n, system);
break;
}
printf("Continue? \n");
scanf(" %d", &ch);
}while(ch == 1);
return 0;
}
解决方案
数组没有赋值运算符。
在这样的陈述中
action_type[10] = "ON";
system_type[10] = "COLD";
room[10] = "EMP";
似乎您想用字符串文字分配数组。但是实际上,您正在尝试使用指向字符串文字的第一个字符的指针来分配数组的不存在元素。
您需要的是将字符串文字复制到数组中,例如
strcpy( action_type, "ON" );
strcpy( system_type, "COLD" );
strcpy( room, "EMP" );
如果您不打算更改数组的元素,那么您可以只使用指针而不是字符数组
char *action_type;
char *system_type;
char *room;
在这种情况下,像这样的陈述
action_type = "ON";
system_type = "COLD";
room = "EMP";
将是正确的。
甚至用限定符 const 声明指针
const char *action_type;
const char *system_type;
const char *room;
在这种情况下,您还需要更改函数声明
void SystemAction(char* action_type, char* system_type, char* room, bool power);
到以下声明
void SystemAction( const char* action_type, const char* system_type, const char* room, bool power);
推荐阅读
- javascript - 使用 CSS 滚动行为时如何从 URL 中删除#id
- c++ - _wmemcpy 替换 64 位程序
- node.js - 从另一个控制器向控制器发布数据
- reactjs - 在 react-native 中使用导航发送参数
- javascript - vehicle.stop 不是函数 p5.js
- inno-setup - 使用 Inno Setup 将多个文件关联注册到同一个可执行文件
- python - 如何创建一个以元组为参数的函数,然后在不使用 sum() 的情况下找到元组中整数的总和?
- python - Dataframe.copy(deep=False) 浅拷贝与仅将一个数据帧分配给另一个数据帧之间是否存在处理/内存差异?
- erlang - Erlang Cowboy 在一台机器上使用不同的端口运行两个 Web 服务器
- firebase - 在 recyclerview 上检索的 Firestore 数据未显示,我单击片段上的 EditText 搜索栏