我正在尝试创建一个函数来初始化结构并将其作为返回值传回,但我无法使其工作。我哪里弄错了?我收到段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char *name;
} Object;
Object object_ctor(int id, char *name);
int main()
{
Object x;
x = object_ctor(1, "Alex");
printf("%s\n", x.name);
return 0;
}
Object object_ctor(int id, char *name)
{
Object y;
y.id = id;
y.name = *name;
return y;
}
最佳答案
Where did I make a mistake?
这是一行:
y.name = *name;
由于几个原因,这是错误的。
您正在将
char
、*name
分配给char*
、y.name 类型的变量
。它违反了指针赋值运算符的约束。来自 C11 标准:
6.5.16.1 Simple assignment
Constraints
1 One of the following shall hold:
...
— the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
— the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of
void
, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;— the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant; or
该赋值的 RHS 不满足上述任何约束条件。
当您将该值视为空终止字符串时
printf("%s\n", x.name);
你遇到了未定义的行为。
您可以通过调高编译器的警告级别来检测此类错误。使用 gcc -Wall
编译时,我收到以下警告。
soc.c: In function ‘object_ctor’:
soc.c:26:12: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
y.name = *name;
^
你需要使用类似的东西:
y.name = strdup(name);
如果 strdup
在您的平台上不可用,那么实现起来并不难。您也可以在 Web 上轻松找到实现。
关于c - 通过函数的返回值初始化 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835012/