Addressing your question in comments under first answer: " why it's not possible to directly assign an array of integers to a previously dynamically allocated pointer to an int array", It is also possible to use this approach (which does not use dynamically allocated memory, but does use a pointer type set to the address of array:
int initial_values[] = {452,35,351,53,66};
int *pMyArray = &initial_values[0]; //sets pointer to address of array[0]
Now you have a pointer type pointing to valid memory containing the same content without memory allocation, and without the need to free allocated memory.
( This exact method is also described here ).
Edit To answer question in comments "What's the point of this?...
... If you don't need it to be dynamic, you can just use initial_values as a pointer."
The short answer is to provide compatibility with certain function prototypes, while not requiring dynamic allocation. The pointer type will compile and run, the array type will not. i.e. even though initial_values
points to the address of the array, &initial_values
does not make it compatible to int **a
, while &pMyArray
is compatible.
The following illustration uses s_test test
and s_test *p
as types as replacements to initial_values
and pMyArray
:
typedef struct {
int iVal;
double dVal;
char sVal[10]
}s_test;
#define SIZE 5
void func(s_test **t, size_t size)
{
const char *new[10] = {"new1","new2","new3","new4","new5"};
for(int i=0;i<size;i++)
{
(*t)[i].iVal *=10;
(*t)[i].dVal *=10.0;
strcpy((*t)[i].sVal, new[i]);
}
}
int main(void)
{
s_test test[SIZE] = {{1, 1.0, "string1"},
{2, 2.0, "string2"},
{3, 3.0, "string3"},
{4, 4.0, "string4"},
{5, 5.0, "string5"}};
s_test *p = &test[0];
func(&p, SIZE); //this works using pointer to pointer
func(&test, SIZE);//run-time error, general protection
return 0;
}