string.h 和 strncpy 与 C 中的指针

string.h and strncpy with pointers in C

我正在尝试创建一个由用户输入创建的列表,其中包含一个具有一个 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 成员。

下一行使用了未定义的namelastn

printf("Age %d, name %s and last name %s", current->age, strncpy(current->name, name, strlen(name)), strncpy(current->lastn, lastn, strlen(lastn)));

不清楚您在此处调用 strncpy 的目的是什么。使用就足够了:

printf("Age %d, name %s and last name %s", current->age, current->name, current->lastn);

此外,while(current) 将永远 运行,因为您没有在循环中更改 current。使用:

while(current)
{
   printf("Age %d, name %s and last name %s", current->age, current->name, current->lastn);
   current = current->next; // Need this
}

fill_structure中,而不是:

scanf("%s", &s->name);
scanf("%s", &s->lastn);

使用

scanf("%s", s->name);   // Drop the &
scanf("%s", s->lastn);