c - 通过函数的返回值初始化 C 结构

标签 c structure

我正在尝试创建一个函数来初始化结构并将其作为返回值传回,但我无法使其工作。我哪里弄错了?我收到段错误。

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

由于几个原因,这是错误的。

  1. 您正在将 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 不满足上述任何约束条件。

  2. 当您将该值视为空终止字符串时

    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/

相关文章:

PHP删除结构内数组中的重复结果

c++ - 结构和文件

c - scanf ("%[^\n]s")对于普通变量可以正常工作,但对于 C 中的结构变量不起作用

c - 如何将作为宏操作结果的宏字符串化?

c - 传递给函数的 malloc 数组的地址 - 段错误

我可以使用变量名称列表动态访问变量吗?

c - 有趣的 strcmp 实现失败。 (C)

c - 段错误(核心已转储): Error while returning from function

php - 我在哪里保存 Zend_Form 文件?

c++ - 如何在 VC 6.0 中对结构数组进行排序