I am trying to create a dynamic array of size 32, and then read intergers from some file, and store them in the array. When the array gets filled up, then double its size (create another of twice the size, copy elements to it from old array and free old array) till the input file is exhausted.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define limit 32
int main (int argc, char *argv[]) {
FILE *file = fopen ("myFile1.txt", "r");
int i = 0, num;
int *B, *C;
B = malloc (sizeof (int) * limit);
while (fscanf (file, "%d", &num) > 0) {
if (i < limit) {
B[i] = num;
i++;
}
else {
C = malloc (sizeof (int) * 2 * limit);
memcpy (C, B, limit * sizeof (int));
free (B);
B = C;
B[i] = num;
i++;
limit = limt * 2;
i++;
}
}
return 0;
}
I am getting an error like: "lvalue required as left operand of assignment" and 2nd: "segmentation fault".
Since, I am trying to explore new possibilities related to dynamic arrays, to increase my knowledge; help me out by modifying the code.
Any help will be highly appreciated.
realloc():limit = limit * 2; B = realloc(B, limit*sizeof(int));. No need to create a temporary array calledC.limita variable, not a macro.