Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It looks like you are trying to create an array of <code>struct myStruct</code>s. There are a few ways to do so. The first is to allocate the structs on your stack ala:</p> <pre><code>struct myStruct p[N]; </code></pre> <p>where <code>N</code> is some positive integer value. Note that by declaring this array on the stack, once your program leaves the scope of wherever this array was declared in, the array and all its contents become lost. Example:</p> <pre><code>struct myStruct foo(int N) { int i; struct myStruct p[N]; for(i = 0; i &lt; N; i++) p[i].intVar = i; for(i = 0; i &lt; N; i++) //Prints value of intVar of each struct myStruct on a different line printf("%d\n", p[i].intVar); // Returns p but the moment the scope returns to the main function, p // ceases to exist return p; } int main() { struct myStruct p[10] = foo(10); // This gives you an error as the program has no notion of p outside the scope // of foo printf("%d\n", p[5].intVar); } </code></pre> <p>The other option is to allocate the array onto the heap ala:</p> <pre><code>struct myStruct **p = malloc(N * sizeof(struct myStruct *)); </code></pre> <p>Note that constructing an array like this means you have to also allocate space on the heap for each struct in the array. Example:</p> <pre><code>struct myStruct** foo(int N) { struct myStruct **p = malloc(N * sizeof(struct myStruct *)); int i; for(i = 0; i &lt; N; i++) p[i] = malloc(sizeof(struct myStruct)); return p; } int main() { struct myStruct **p = foo(10); p[5]-&gt;intVar = 10; // This is now valid because p and its elements // exist on the heap until you free them printf("%d\n", p[5]-&gt;intVar); // For every malloc you must have a free, lest // you run into memory leaks int i; for(i = 0; i &lt; 10; i++) free(p[i]); free(p); } </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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