Trisha
Trisha

Reputation: 67

Create Dynamic Array in c

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.

Upvotes: 1

Views: 1876

Answers (1)

Claudio Cortese
Claudio Cortese

Reputation: 1380

You can actually allocate more memory for your array using realloc() :

void *realloc(void *ptr, size_t size)

Instead of doing that :

  {
    C=malloc(sizeof(int)*2*limit);
    memcpy(C,B,limit*sizeof(int));
    free(B);
    B=C;
    B[i]=num;
            i++;
            limit=limt*2;
    i++;
       }

You can simply do :

B = realloc(B,new_size_in_bytes);

Talking about your code:

The preprocessor command #define will replace every occurrence of the word "limit" with the value associated to it (32, in this case) before the compilation. So you can't really change the value of a macro during run-time. If you wish to do that my advice would be not to define limit but use a variable instead. About the segfault I'm not having one. Be sure to have the file called "myFile1.txt" in the same folder where the .c file is, also check if you misspelled it.

Upvotes: 3

Related Questions