I have the following variable "places" which is a ptr to a dynamic array of string locations:
uint32_t* places;
I would like for my function to return a DUPLICATE pointer of type (uint32_t*)
My current attempt:
uint32_t arrCpy = malloc((numberOfElements) * sizeof(uint32_t));
memcpy(arrCpy, places, sizeof(uint32_t*)*numberOfElements);
return arrCpy;
Please explain what I am doing wrong and how to resolve this issue? I am receiving a segmentation fault using gcc.
Correction:
Goal is to take a uint32_t and make a duplicate uint32_t
"Note that the function returns a duplicate
of the array of locations for the key, not a pointer to the original array stored in the hash table. The rationale for this is that
returning a pointer to the original array would be dangerous because it would allow the user to directly modify the original
array."
3
Answers
arrCpy
needs to be a (double) pointer. If it’s an array of pointers, you also need to allocate space fornum
pointers, not values.uint32_t* places;
is not an array of pointers, it’s a pointer touint32_t
, a number. Generally, to have an array ofsomething
, you should have an pointer pointing tosomething
. So you may want to declare yourplaces
likeuint32_t** places;
, and so is arrCpy.—edited—
If you want to duplicate an array of
uint32_t
:You can see no matter what array you want to duplicate, you create an pointer, allocate its memory then copy it, and then return that pointer.
—edited—
an complete code
If you wrote exactly what you need, it is just a pointer pointing to the same array. But it is not an array of strings, it is an array of pointers to 32-bits
int
places
has the address of the start of the array of pointers, so you just need to copyplaces
.places
. This is whymain()
is declaredargc
comes just in time with the number of pointers, so the system can build the array and you can iterate over them.if you know the size and need to duplicated everything
This is the common scenario, as the source of
places
addresses can go out of scope and invalidate the full block thatplaces
points to. Since the new array will point to the same locations you need to go in 2 steps:you need to allocate an area to hold all the pointers. The size is the number of pointers times the size of a pointer in your machine. The pointers are aligned in memory so you can copy the whole block at once using
memcpy()
you need to create a pointer that points to the new array. No need to use
uint32_t**
You can reverse the steps.
But you need to know how many pointers
places
points to, and may be more practical just go the system way and write a pair likeint argc, char** argv