gpt4 book ai didi

c - 函数:char* 与 int 表达式的间接级别不同

转载 作者:行者123 更新时间:2023-11-30 21:09:51 25 4
gpt4 key购买 nike

我正在开发一个用户输入信息的函数,我希望将该信息复制到数组中。这是我到目前为止所拥有的:

struct drone_info /* structure declaration */
{
int number; /* drone number */
int type; /* drone type */
char pilot_name[30]; /* pilot name */
};

struct drone_info drone[100]; /* declare array for struct */

void add_a_drone();

void add_a_drone()
{
int number; /* drone number */
int type; /* drone type */
char pilot_name[30]; /* pilot name */

printf("\nPlease enter the drone number."); /* prompt user for drone number */
scanf("%d", &number); /* scan drone number */
printf("\nPlease enter the drone type."); /* prompt user for drone type */
scanf("%s", &type); /* scan drone type */
printf("\nPlease enter the pilot name."); /* prompt user for pilot name */
scanf("%s", &pilot_name); /* scan pilot name */

strcpy(drone[number - 1].number); /* error occurs here */
strcpy(drone[type - 1].type, type);
strcpy(drone[pilot_name].pilot_name, pilot_name);
printf("\nThe new drone has been added successfully.\n\n");

number++; /* increment drone number by 1 */

最佳答案

请注意,strcpy(顾名思义)仅适用于字符串,而不适用于其他数据类型。在索引数组时,您还应该使用一致的 size_tint,而不是 char*

所以这些行:

strcpy(drone[number - 1].number); /* error occurs here */
strcpy(drone[type - 1].type, type);
strcpy(drone[pilot_name].pilot_name, pilot_name);

确实应该

drone[current].number = number; /* no more error */
drone[current].type = type;
strcpy(drone[current].pilot_name, pilot_name); /* you can still use strpy here! */

其中current是一个int,用于跟踪当前无人机

关于c - 函数:char* 与 int 表达式的间接级别不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33138426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com