我正在尝试创建一个用户输入创建的列表,其中包含一个具有一个 int 和两个字符串的结构。但我似乎无法正确使用 string.h 中的 strncopy 。 我应该使用参数的顺序,例如: 1. 指针名称 2.要复制的字符串 3.字符串长度
我收到的错误说“name”和“lastn”这些字符串没有声明......那么我在这里缺少什么?
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stats
{
int age;
char name[25];
char lastn[25];
struct stats *next;
};
void fill_structure(struct stats *s);
struct stats *create(void);
int main()
{
struct stats *first;
struct stats *current;
struct stats *new;
int x = 5;
//create first structure
first = create();
current = first;
for(x=0; x<5; x++)
{
if(x==0)
{
first = create();
current = first;
}
else
{
new = create();
current->next = new;
current = new;
}
fill_structure(current);
}
current->next = NULL;
current = first; //reset the list
while(current)
{
printf("Age %d, name %s and last name %s", current->age, strncpy(current->name, name, strlen(name)), strncpy(current->lastn, lastn, strlen(lastn)));
}
return(0);
}
//fill a structure
void fill_structure(struct stats *s)
{
printf("Insert Age: \n");
scanf("%d", &s->age);
printf("Insert Name: \n");
scanf("%s", &s->name);
printf("Insert Last Name: ");
scanf("%s", &s->lastn);
s->next = NULL;
}
//allocate storage for one new structure
struct stats *create(void)
{
struct stats *baby;
baby = (struct stats *)malloc(sizeof(struct stats));
if( baby == NULL)
{
puts("Memory error");
exit(1);
}
return(baby);
};
最佳答案
strncpy(current->name, name, strlen(name))
^ ^
您没有声明任何名为name
的对象。在您的程序中,唯一的 name
标识符是 struct stats
结构类型的 name
成员。
关于c - C 中带有指针的 string.h 和 strncpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850512/