1

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:

  • "parentheses missing before [ "
  • "int [] append(struct List a2, int a)"
  • implicit function used in "int narr [] = append(a, 50)"
4
  • Can you please provide the error that you are getting in the question so one can get the idea about the issue? Also try to describe what you are trying to do or accomplish. Commented Jan 19, 2021 at 7:14
  • A bit of proper formatting would be great too. Commented Jan 19, 2021 at 9:39
  • I am getting "parentheses missing before [ " here "int [] append(struct List a2, int a)" and implicit function used in "int narr [] = append(a, 50)" this line. Commented Jan 19, 2021 at 10:28
  • Welcome to Stack Overflow. Please have a read of the formatting help page about how to format code properly (its unworkable in its current state). Please also tag the question with the right tags, e.g. c++ -- this is very important to draw attention to the question, and for future reference. Also remember that you can edit your question at any time to enhance it, consider checking out the tour and the question guide here to help enhance your question. Commented Jan 19, 2021 at 11:58

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.