pilkington pilkington - 1 month ago 12
C Question

Changing an int value in struct which is in linked list

I have a struct:

struct person{
char* name;
char* surname;
int age;
};


And I use this struct inside another struct for linked list:

struct listNode {
struct person data;
struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;


I am trying to insert one struct into the linked list. After that I want to get this struct by index and change the age value. In main, I have these codes:

int main() {

ListNodePtr startPtr = NULL;

struct person p;

p.age = 22;
p.surname = "Pilkington";
p.name = "Anthony";

insert(&startPtr, p);
printf("Age1:%d\n", p.age);

struct person p2 = getStruct(&startPtr, 0);
p2.age++;
printf("Age2:%d\n", p2.age);

struct person p3 = getStruct(&startPtr, 0);
printf("Age3:%d\n", p3.age);

return 0;
}


Now, my insert function and getStruct function are working correctly. But I cannot increment the age value. My output is:

Age1:22
Age2:23
Age3:22


I want to make the Age3 23. In insert function, I already allocate memory with malloc, but why can't I change the first value? How can I change this value without removing/adding the node from list?

I search the subject but I cannot find the answer that I want. So, If you can help me I appreciate that.

---EDIT-----
Sorry for not posting getStruct method, I am adding it below:

struct person getStruct(ListNodePtr *sPtr, int index) {
ListNodePtr currentPtr;
struct person c;

int counter = 0;

currentPtr = *sPtr;

while (currentPtr != NULL) {
if (counter == index) {
c = currentPtr->data;
}
counter++;
currentPtr = currentPtr->nextPtr;
}

return c;
}

Answer

Here:

struct person p2 = getStruct(&startPtr, 0);

You return a person by value, which is to say you make a copy. Then you modify the copy, not the original. You'll need to do this instead:

struct person *p2 = getStruct(&startPtr, 0);
p2->age++;
printf("Age2:%d\n", p2->age);

That is, return a pointer, which you can use to modify what it points to. This also requires a slight change to getStruct(), whose code you haven't posted.