PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     c, c-strings, dereference, pass-by-reference, pointers     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing