Wednesday, July 6, 2022

[FIXED] How to properly deference a char** pointer passed as an address to functions?

Issue

I am writing a program that uses char ** to setup a multidimensional array. I then pass the address of the char ** to another function to play with.

How do I properly deference ** pointers after they have been passed via address to another function?

ERROR
array of c string
Segmentation fault

int test(char *** strings){
    puts(*strings[0]);
    puts(*strings[1]);
    return 1;
}

int main(void) {

    char arr[][25] =
    { "array of c string",
    "is fun to use",
    "make sure to properly",
    "tell the array size"
    };
    
    
  char ** strings = (char**)malloc(2 * sizeof(char*));
  
  strings[0] = (char*)malloc(25 * sizeof(char));
  strcpy(strings[0], arr[0]);
  
  strings[1] = (char*)malloc(25 * sizeof(char));
  strcpy(strings[1], arr[1]);
  
  test(&strings);

  return 1;
}

*Mallocs are casted incase someone plugs this into a C++ playground


Solution

This works:

int test(char *** strings){
    puts((*strings)[0]);
    puts((*strings)[1]);
    return 1;
}

Because [] binds more tightly than * and you need to dereference first. See https://en.cppreference.com/w/c/language/operator_precedence



Answered By - user14215102
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.