user2330482
user2330482

Reputation: 1103

C adds a reference to array, not a value

I am new to C and have never done anything with a non-OOP language.

I have an array of structs. It is global to the class and I parse a json with the results ending up in above mentioned array. I create an object (?) based on the struct that offers one property for every entry. After adding the items, the array turned out to have the same value on all of the positions.

I did remember C being tricky when it comes to values and pointers/references so I have made a little test to see whether the array actually only took the reference:

typedef struct  {
    char* name;
} ww_item ;

char nameW[40];

// iterating through json {
// strcpy(nameW, data);

    ww_item w = { nameW };

    ww_items [ position ] = w;

    strcpy(nameW, "d"); //replaces the "Hello" with "d" in all previous ww_items

Obviously it does, which explains why my array ends up being a repetition of the last element that has been added to it instead of listing all the different strings I have added to it.

I am unable to find any short information on this and unfortunately my deadline is too close to read through a whole C book now. I'm pretty sure that my assumptions so far are true but now I do not know what to search for/ to look for in order to solve this problem.

I'm okay with an ugly solution or workaround but at the moment I am just stuck with this.

Thank you for your help.

Upvotes: 0

Views: 57

Answers (1)

Barmar
Barmar

Reputation: 781058

Change the name member from a pointer to an array.

typedef struct  {
    char name[40];
} ww_item ;

and then use strcpy()

strcpy(ww_items[position].name, w);

There's no need for the w variable.

Upvotes: 1

Related Questions