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
dhutturi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
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;
Try
void* b = malloc(3 * sizeof(int));
std::cout << "_msize: " << _msize(b);
int a[3]; //implicit malloc of 3 * int
std::cout << "size: " << sizeof(a);
3