Note that there are some explanatory texts on larger screens.

plurals
  1. POC - Array of strings (2D array) and memory allocation gets me unwanted characters
    primarykey
    data
    text
    <p>I have a tiny problem with my assignment. The whole program is about tree data structures but I do not have problems with that.</p> <p>My problem is about some basic stuff: reading strings from user input and then storing them in an array <em>list</em>.</p> <pre><code>char str[1000]; fgets(str, 1000, stdin); int x = 0; int y = 0; int z = 0; char **list; list = (char**)malloc((x+1)*sizeof(char)); list[x] = (char*)malloc((y+1)*sizeof(char)); while(str[z] != '\n') { list[x][y] = str[z]; z++; if(str[z] == ',') { x++; y = 0; list = (char**)realloc(list, (x+1) * sizeof(char*)); list[x] = (char*)malloc((y + 1)*sizeof(char)); z++; if(str[z] == ' ') // Skips space after the comma { z++; } } else if(str[z] == '\n') { break; } else { y++; list[x] = (char*)realloc(list[x], (y+1)*sizeof(char)); } } </code></pre> <p>I pass this list array into another function. As an example, inputs could be something like </p> <pre><code>Abcde, Fghijk, Lmnop, Qrstu </code></pre> <p>and I am trying to split each of these words into the array <em>list</em>.</p> <pre><code>Abcde Fghijk Lmnop Qrstu </code></pre> <p>When I try to output the strings I sometimes get weird, excessive characters such as upside down question marks and numbers.</p> <pre><code>printf("%s ", list[some_number]); </code></pre> <p>gets me</p> <pre><code>Fghijk¿ </code></pre> <p>or</p> <pre><code>Fghijk\200 </code></pre> <p>All of my program works as expected except for this minor problem which I am having trouble solving. Even with the same exact inputs the bugs may or may not appear. I am guessing it has to do with memory allocation?</p> <p>Thanks for your help!</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.
 

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