Note that there are some explanatory texts on larger screens.

plurals
  1. POdynamic array of structs in C
    text
    copied!<p>I am trying to learn about structs, pointers, and dynamic arrays in C. I don't understand how to create a dynamic array of structs using pointers. My code doesn't work, and I don't know what's wrong with it. I have seen several examples of dynamic arrays, but non with structs. Any help would be appreciated. Please give some explanation, not just code snippets as I do want to understand not just solve this problem. </p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include &lt;string.h&gt; struct *struct_array; int i,m,n,p; struct data { char inputA[20]; char inputB[20]; }; struct data get_data() { struct data thisdata; printf("Please enter input A\n"); scanf("%s", thisdata.inputA); printf("Please enter input B\n"); scanf("%s", thisdata.inputB); return thisdata; } void Output(struct data struct_array, int n) { int index = 0; for(i = 0; i&lt;n ;i++) { printf("%s ", struct_array[i].inputA); printf("%s ", struct_array[i].inputB); } } void resizeArray(int n) { struct_array = (int*)realloc(n*sizeof(int)); } void mainMenu() { printf("Please select from the following options:\n"); printf("1: Add new students to database\n"); printf("2: Display current student database contents\n"); printf("3: exit the program\n"); scanf("%d", &amp;p); if(p == 1) { printf("Please enter the number of students to register:\n"); scanf("%d", &amp;n); resizeArray(n); for(i = n; i&lt;n ;i++) { struct_array[i] = get_data(); } } else if(p == 2) { Output(struct_array, n); } else { free(struct_array); exit(0); } } int main() { struct_array = (int*)realloc(2*sizeof(int)); mainMenu(); } </code></pre>
 

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