0

I would like to add an element at the end of the array. LENGTH(a) is a marco which means the size of the array a . Initial value of the array is {1}. I would like to add all even-number into array.So,the result I want is array = {1,0,2,4},but the result is as the picture shows.

enter image description here

The code is as follows:

#include <stdio.h>
#include <stdlib.h>

#define LENGTH(a) (sizeof(a) / sizeof(*a))

void insert(int *, int);

void main(){
    int size = 1;
    int * array = (int*)malloc(size * sizeof(int));
    array[0] = 1;
    int i;
    int value = 0;

    for(i = 0; i < 5; i++){
        if (i%2 == 0){
            insert(array, i);   
        }       
    }
    for(i = 0; i < LENGTH(array); i++) {
      printf("array[%d] = %d\n", i, array[i]);
   }
}

void insert(int *array, int a){
    array = realloc(array, (LENGTH(array)+1)*sizeof(int));
    printf("length = %d\n", LENGTH(array));
    array[LENGTH(array)] = a;   
}

I'd like to know why this occurs and how to solve it.

bruno
  • 32,421
  • 7
  • 25
  • 37
KatrinaKing
  • 43
  • 2
  • 6
  • 1
    `LENGTH(array)` is wrong, `sizeof(array)` is not what you expect, it is `sizeof(int*)`, you have to give *size* to *insert* and to increment it in *main* or *insert* if received by pointer – bruno Dec 28 '20 at 11:27
  • 1
    Surprise! Arrays are not pointers and vice versa! – Sourav Ghosh Dec 28 '20 at 11:29
  • Your mistake is to name `array` in `insert` the same as `array` in `main` and to assume you can use them in the same way. Change the name of the parameter in `insert` to `parray`, because it is a pointer to `array` in `main`. Then it becomes clear what the problem is. The macro works on an array, but gives an incorrect answer with a pointer. – stark Dec 28 '20 at 11:57

0 Answers0