Raphael Hawk
Raphael Hawk

Reputation: 11

How to use structs in C/C++?

The following is my code and I am getting some errors. Could someone help me understand these errors please?

Struct List :

struct List{
    int size;
    int arr[]; 
};

Append Function :

int [] append(struct List a2, int a) {
    int size = a2.size + sizeof(int);
    int p [size]; //= (int *)malloc(size);
    for(int i = 0; i < size; i++ ){
        p[i] = a2.arr[i];
        if (i > a2.size){
            p[i] = a;
        }   
    }
    return p;
}

Main Function :

int main(){
    int arr[] = {12,313,13,214,23};
    struct List a = {sizeof(arr)/sizeof(int), arr};
    int narr [] = append(a, 50);
    printf("%d\n" , sizeof(arr));   
}

The errors I'm getting are:

Upvotes: 1

Views: 78

Answers (1)

entangled_photon
entangled_photon

Reputation: 457

Most of your problems stem from the List structure:

struct List {
    int size;
    int arr[]; 
};

The line int arr[]; creates a "variable-length array". You have confused this here with a "dynamic array". A variable length array is simply a trail of bytes abstracted to part of a struct.

Your append function does not work because you cannot return an array from a function, much less a variable length array. You also write into uninitiated memory.

To use a variable-length array, first allocate it on the heap. Here we allocate it with 4 elements.

struct List* list = malloc(sizeof(*list) + 4 * sizeof(int));
list->size = 4;
list->arr[0] = 2;
list->arr[1] = 3;
list->arr[2] = 5;
list->arr[3] = 7;

To append an element to the array, we must use realloc.

list = realloc(list, sizeof(*list) + 5 * sizeof(int));
list->arr[4] = 11;

At the end of your program, make sure to free(list).

Upvotes: 1

Related Questions