Note that there are some explanatory texts on larger screens.

plurals
  1. PO2D arrays. First index wrong, all others correct
    primarykey
    data
    text
    <p>I have a weird problem and I'm not sure how to approach it.</p> <p>I'm reading a 50x50 chars textfile and want to write it into a 50x51 dynamic array (filling the 51th slot with '\0').</p> <p>Afterwards I'm printing the entire array onto the console. It should show 50 lines with 50 chars each, as this was the input.</p> <p>It works quite well too - with the exception of the first line. For some reason is always wrong.</p> <pre><code>#define FIELD_SIZE 50 int main(int argc, char** args){ char* data = ReadFile("start.txt"); char** map = (char**) malloc( FIELD_SIZE ); if(map==NULL) __debugbreak(); { int i; for(i = 0; i &lt; FIELD_SIZE; i+=1){ map[i] = (char*) malloc(FIELD_SIZE+1); if(map[i]==NULL) __debugbreak(); //(FIELD_SIZE+1) in order to skip the '\n' at the end of each line. memcpy( &amp;map[i][0], &amp;data[i*(FIELD_SIZE+1)], FIELD_SIZE); map[i][FIELD_SIZE] = '\0'; } } { int i; for(i = 0; i &lt; FIELD_SIZE; i+=1){ printf("%s\n", map[i]); //&lt;-- prints something bad for i==0 } } free(data); return 0; } </code></pre> <p>Here's how my console looks like after program execution: <img src="https://i.stack.imgur.com/UDEN6.png" alt="enter image description here"> The first line is supposed to be "aaaaaaaaaaaaa..." too. So it seems like a bad pointer or something.</p> <p>If I'm reducing FIELD_SIZE to 20 instead (and reading in a 20x20 text file respectively) it works fine, however.</p> <p>I don't see a connection between the array size and the first index not working though. Since malloc never returned 0 there's no problem with allocation.</p> <p>I'm using VS2010 C++ to compile the program, but I have to limit myself to the C subset.</p>
    singulars
    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