我已将我的结构声明为
struct linkedStruct
{
char name;
int size;
enum groupstatus status;
struct linkedStruct* next;
};
我试图将代码中的 char* 名称变量(一串字符)传递到该结构的单个节点中。 例如,用户输入Jon,我希望我的字符名存储字符串Jon。
我在考虑如何解决这个问题时遇到了一些困难。我尝试只是简单地说明(假设我的节点名称是 temp)
temp->name = name;
但是,当我在存储名称值时打印出名称值时,printf 不会返回任何内容。
我最初将它作为 name[30] 在我的结构中,因为我们假设该名称少于 30 个字符,但这最终让我更加困惑,因为在尝试将名称存储到结构中时我不断收到错误使用 for 循环。
我的结构的其他实现
struct linkedStruct
{
char name[30]; //now a character array
int size;
enum groupstatus status;
struct linkedStruct* next;
};
代码是
for(int i = 0; i< sizeof(name); i++){
name[i] = temp->name[i];
//seemed totally wrong to do but I had no idea how to go about it
}
我只是想知道在这两种情况下我将如何存储它,因为我当前的代码不起作用。在我的 name[30] 实现中,我不知道如何声明/访问结构的数组表示法。
最佳答案
这是不可能的。 char
类型的变量只能容纳一个字符。
如果您知道名称限制为 30 个字符,那么您应该这样做
char name[30];
在结构声明中。 C 中的字符串是使用 strcpy()
复制的,因此您可以执行以下操作来设置结构内的名称:
struct linkedStruct temp;
strcpy(temp.name, "hello");
关于c - 在链表结构体中传入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190986/