Home > Software engineering >  C function doesn't modify passed array
C function doesn't modify passed array

Time:11-16

Hi I need help with my C assignment. I need to modify a dynamic 2d array, so I pass a pointer to it to function, unfortunately it seems to not modify it but only copy it and leave it untouched, I have tried everything, can someone help please?

int getUniqueRelMembersCount(universe_t u, relation_t rel, char **members)
{
    int memberCount = 0;

    //count and dynamically populate passed 2d array with unique members of rel

    return memberCount;
}

How I call the function:

char **members = malloc(sizeof(members));
int len = getUniqueRelMembersCount(universe, relations.relations[0], members);
printf("%d\n", len);
printf("%s", members[0]);
for (int i = 0; i < len; i  )
{
     free(members[i]);
}

free(members);

output:

3

Segmentation fault

CodePudding user response:

Despite having the same name, the variable named members in your function and the variable named members in the caller are different variables.

You change members in the function (members = realloc(...)), but don't propagate this change to the caller.

Simplified demo:

void f(int members) {
   printf("%d\n", members);   // 2
   members = 3;
   printf("%d\n", members);   // 3
}

int main(void) {
   int members = 2;
   printf("%d\n", members);   // 2
   f(members);
   printf("%d\n", members);   // 2
   return 0;
}

You could return the modified value. In this case, it's better to pass a pointer to the variable.

int f(int *membersPtr) {
   printf("%d\n", *membersPtr);   // 2
   *membersPtr = 3;
   printf("%d\n", *membersPtr);   // 3
}

int main(void) {
   int members = 2;
   printf("%d\n", members);   // 2
   f(&members);
   printf("%d\n", members);   // 3
   return 0;
}

In your full program, a pointer to the variable would have type char***.

CodePudding user response:

Your following code shouldn't work:

char **members = malloc(sizeof(members));
int len = getUniqueRelMembersCount(universe, relations.relations[0], members);

because:

  1. you cannot use 'member' value to initialize 'member';
  2. malloc returns signle pointer, but not double pointer.

Try this:

int members_count = 10;
char *members = malloc(members_count);
int len = getUniqueRelMembersCount(universe, relations.relations[0], &members);
  • Related