Note that there are some explanatory texts on larger screens.

plurals
  1. POSegmentation fault by writing in a 2D Array
    primarykey
    data
    text
    <p>I have a small memory access problem in my program and I do not find the error, maybe someone could help me. </p> <p>I have created a new type to store rgb color values. That type looks like:</p> <pre><code>typedef struct pixel { unsigned char r; unsigned char g; unsigned char b; } pixel; </code></pre> <p>In my main program I create with calloc a 2D dynamically array, to store the red color information’s.</p> <pre><code>pixel **pixelvalue = (pixel **) calloc(imginformation.width, sizeof(pixel)); for (i = 0; i &lt; imginformation.width; i++) { pixelvalue[i] = (pixel *) calloc(imginformation.height, sizeof(pixel)); } </code></pre> <p>After that I call my function, which read the color values and who should safe them to the array. The function gets as parameter the array.</p> <pre><code>ReadFile(file, imginformation (Stuff like height and so one), pixelvalue (The calloc array)); </code></pre> <p>In that function I try to write the values with </p> <pre><code>pixelvalue[i][j].r = (unsigned char)fgetc(in); </code></pre> <p>Here I get the memory access error, what did I wrong?</p> <p><strong>Edit</strong></p> <p>Hi, first of all sorry about the missing language, I was a little bit tired yesterday :).</p> <p>To understanding, I created an array of pixel and the elements are pointing to another array of pixel? Something like <code>[Point to another 1D array pixel]</code>?</p> <p>With pixel <code>**pixelvalue = calloc(imginformation.width, sizeof(pixel *));</code> I create <code>imginformation.width</code> numbers of pointers from type pixel and each pointer show to pixel, right?</p> <p>It would be awesome if you could explain it a little bit more, if I’m wrong. I would really like to understand it. </p> <p>@carl-norum What do you mean with:</p> <blockquote> <p>"you shouldn't be casting the return values of calloc(). Doing so can hide bugs with #include that could come back to bite you down the road". </p> </blockquote> <p>? I use the alloc space as parameter for a function, not as return value.</p> <p>Thanks for your help!</p> <p>Greetz</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