string.h和strncpy,带有C中的指针

时间:2015-09-29 17:44:54

标签: c list pointers strncpy

我试图创建一个用户输入创建列表,其中包含一个带有一个int和两个字符串的结构。但我似乎无法正确使用string.h中的strncopy。 我应该使用参数的顺序,如: 1.指针名称 2.要复制的字符串 3.字符串长度

我得到的错误是' name'并且' lastn'哪些是字符串未声明...所以我在这里缺少什么?

CODE

#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);
};

2 个答案:

答案 0 :(得分:2)

strncpy(current->name, name, strlen(name))
                         ^           ^

您没有声明任何名为name的对象。在您的计划中,唯一的name标识符是name结构类型的struct stats成员。

答案 1 :(得分:1)

以下行使用未定义的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);