Note that there are some explanatory texts on larger screens.

plurals
  1. POMulti-dimensional char array prints within function, but not when passed to another function
    primarykey
    data
    text
    <p>I am attempting to write data into a multi-dimensional array, and then pass the array as a <code>const char**</code> to another function. When I print the <code>char*</code> locally in the function in which it is declared, everything works as expected. But, when I try to print the array of <code>char*</code> in another function, they are all empty strings. </p> <p>I am using the following code:</p> <pre><code>void my_print (const char** lines, unsigned int num) { int i = 0; for (i = 0; i &lt; num; i++) { fprintf(stderr, "lines[%d]: %s", i, lines[i]); } } void my_func () { char cfg[2][200]; unsigned int value = 5; snprintf(cfg[0], 200, "one two three\n"); snprintf(cfg[1], 200, "my value = %u\n", value); fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]); my_print((const char**) cfg, 2); } </code></pre> <p>This results in the following output:</p> <pre><code>lines[0] = one two three lines[1] = my value = 5 lines[0]: lines[1]: </code></pre> <p>If instead, of the given <code>my_func</code>, I use the following:</p> <pre><code>void my_func () { char* cfg[2]; unsigned int value = 5; cfg[0] = malloc(200); cfg[1] = malloc(200); snprintf(cfg[0], 200, "one two three\n"); snprintf(cfg[1], 200, "my value = %u\n", value); fprintf(stderr, "lines[0] = %slines[1] = %s\n", cfg[0], cfg[1]); my_print((const char**) cfg, 2); } </code></pre> <p>Then, everything works, and I get:</p> <pre><code>lines[0] = one two three lines[1] = my value = 5 lines[0]: one two three lines[1]: my value = 5 </code></pre> <p>So, what is happening in the background here? Why do I need to use <code>malloc</code> in order for <code>my_print</code> to be able to print my strings?</p> <p>Thanks you</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload