简体   繁体   中英

Initialize C struct by return value of a function

I am trying to make a function to initialize a structure and pass it back in its return value, but I cannot make it work. Where did I make a mistake? I get a segmentation fault error.

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

This is the line:

y.name = *name;

It is wrong for couple of reasons.

  1. You are assigning a char , *name , to a variable of type char* , y.name . It violates the constraints of the assignment operator for pointers.

    From the C11 standard:

    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

    The RHS of that assignment does not satisfy any of the above constraints.

  2. When you treat that value as a null terminated string in

     printf("%s\\n", x.name); 

    you run into undefined behavior.

You can detect errors like this by turning up the warning level on your compiler. I get the following waring when compiling with 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;
            ^

You need to use something like:

y.name = strdup(name);

If strdup is not available on your platform, it's not too hard to implement. You can find an implementation easily on the web also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM