Search code examples
cdata-structurespointersargument-passingstrdup

Passing a structure by reference and manipulating it


typedef struct unit_class_struct {
    char *name;
    char *last_name;
} person;


int setName(person *array) {

    array[0].name = strdup("Bob");
    array[1].name = strdup("Dick");

    return 1;
}

int setLastName(person *array) {

    array->last_name = strdup("Sanchez");
    array++;
    array->last_name = strdup("Clark");

    return 1;
}

int main()
{
    person array[10];
    person *pointer;
    pointer = array;
    setName(pointer);
    setLastName(pointer);
    printf("First name is %s %s\n", array[0].name, array[0].last_name);
    printf("Second name is %s %s\n", array[1].name, array[1].last_name);
    while(1) {}
    return 0;
}

This is some example code I came up with to play around with structures. Notice the way I set the name in setName and the way I did it in setLastName.

Both work, but I'm curious whats the difference between the two ways I did it?

Is one way better than the other?

Also is strdup necessary in this example? If not, would it be necessary if I was setting array.name to random sized variables rather than string literals?


Solution

  • Using the indexed approach is slightly clearer than using the pointer arithmetic, in my opinion but either works. I suspect the code the compiler generates for each is quite similar in both instances.

    strdup is necessary in this instance if you're working with variables because you do not allocate memory to save your string values in in the person struct. If you'd already allocated space for those strings when either of your setters was called, strcpy (strcpy_s, preferably) would be sufficient.

    When working with literals as you are in your example, strdup is not necessary: you can assign directly to the char*.