cpointersmalloc

malloc() doesn't allocate what I expect it to


I have two integer pointers, a and b. I use the following line:

int* b = malloc(3 * sizeof(int));

I expect calling sizeof(b) to return 3 * sizeof(int) which equals 12, but that isn't the case and it returns 8.

To a I would like to allocate the elements present in b, with another element appended (at the end of it). If advice is given regarding how to allocate multiple, it would be appreciated.

My questions, summarised are: Why is malloc showing the behaviour described in the first paragraph and how to essentially append to an integer array


Solution

  • to allocate the elements present in b, with another element appended

    // Allocate
    int *a = malloc(4 * sizeof(int)); 
    // or better as 
    int *a = malloc(sizeof a[0] * 4); 
    
    // Copy the data pointed to by `b` to `a`.
    memcpy(a, b, sizeof a[0] * 3);
    
    // Assign.
    a[3] = 42;