gpt4 book ai didi

c - C 结构体数组中的指针

转载 作者:行者123 更新时间:2023-11-30 19:34:37 25 4
gpt4 key购买 nike

我打算用这段代码实现的是从主函数中获取一个字符串字符,然后将其分配给结构中特定索引处的名称。示例:它应该为我打印 Name=> Charles Key=> 0下一行将是 Name=> George Key=> 1 ...等等。但它宁愿选择输入的姓氏并使用它,尽管我的结构是一个结构数组。我也不想直接将其放在主要位置...例如 scanf("%s", &node[i].name)因为在我正在构建的实际项目中,我将根据用户输入的内容计算 i 。请帮帮我。谢谢

#include<stdio.h>
#include<stdlib.h>
typedef struct{
int key;
char *name;
}test;

int main(){
test node[5];

int i;
char see[10];
//for loop for taking string character in see and then assigning name in structure to it
for(i=0; i<5; i++){
printf("Enter name\t");
scanf("%s", &see);
//assigns name in structure index i to see
node[i].name=see;
node[i].key=i;
}
//prints data stored in structure
for(i=0; i<5; i++){
printf("Name=> %s\t\tKey=> %d",node[i].name, node[i].key);
}
return 0;
}

最佳答案

按以下方式更改...

  1. char *name; ----> char name[10];
  2. scanf("%s", &see); ----> scanf("%s", see);
  3. node[i].name=see; ----> strcpy(node[i].name, see);

关于c - C 结构体数组中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646932/

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