In you declare MyArray as a doble pointer
Data **MyArray = malloc(sizeof(Data) * 10);
the result of malloc should be casted to the double pointer:
struct Data **MyArray = (struct Data**) malloc(sizeof(Data) * 10);
But providing a single pointer to the array of struct Data should be sufficient for your needs:
void CopyGlobalArray (void *ArrayBuffer)
{
memcpy(ArrayBuffer, DataArray, sizeof(DataArray));
}
This is how could you use it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Data
{
char * FirstName;
char * LastName;
};
// global structure
struct Data DataArray[] = { {.FirstName = "Fred", .LastName= "Smith"}, {.FirstName = "Eva", .LastName= "White"}, {.FirstName = "John", .LastName= "Rock"} };
void CopyGlobalArray (void *ArrayBuffer)
{
memcpy(ArrayBuffer, DataArray, sizeof(DataArray));
}
void print(struct Data *array )
{
for(size_t i=0; i < sizeof(DataArray)/sizeof(DataArray[0]); i++)
{
printf("%s", array[i].FirstName);
printf("%s\n", array[i].LastName);
}
}
struct Data *function()
{
struct Data *MyArray = (struct Data *) (malloc (sizeof(DataArray) ) );
CopyGlobalArray (MyArray);
// Copied array
printf("\nMyArray:\n");
print(MyArray);
return MyArray;
}
int main(void)
{
// Original
printf("\nDataArray:\n");
print(DataArray);
struct Data *MyArray1 = function();
printf("\nMyArray1:\n");
print(MyArray1);
free(MyArray1); // free the array allocated inside function()
return 0;
}
Output:
DataArray:
FredSmith
EvaWhite
JohnRock
MyArray:
FredSmith
EvaWhite
JohnRock
MyArray1:
FredSmith
EvaWhite
JohnRock
ArrayBufferlooks like triple pointer, not double. also)is missing for thememcpycall. Please post your real code.ArrayBufferis a double pointer tovoid*.memcpycall with the parameters you pass? That just seems wrong to me,*ArrayBufferis not an array (or a pointer to the first element of an array) ofDataelements.void *andmemcopy.10 * sizeof(struct Data)bytes. Themallocfunction returns a pointer to the first byte. A pointer, not a pointer to a pointer. And using the address-of operator to pass a pointer toMyArraymakes no sense.