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

标签 c list pointers strncpy

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

相关文章:

python - 如何在 Python 中包裹字符串或数组并对包裹的字符串或数组进行切片?

C# Xml 序列化 List<T> 具有 Xml 属性的后代

C:将具有数组的指针传递给函数时,会出现运行时错误。为什么?

c++ - ContextMenu 项目扩展在 Windows 7 中不起作用

c - 如何在 C 中编写 pragma

java - 使用java递归搜索Hashmap列表中的值

c++ - 指针导致访问冲突

C 对应于 C++ find_first_not_of?

c++ - 蓝牙 4 (BLE) 似乎无法在许多设备上访问(例如 HP 15-d004au 笔记本电脑)

c++ - 是否可以将指针传递给文字?