I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don’t get some important thing, help me please.
So, If I do that everything works fine:
void alloc(char **p, int n)
{
*p = new char[n];
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
for(int i = 0; i<(n - 1); i++)
ptr[i] = '1';
ptr[n - 1] = '\0';
printf("%s", ptr);
return 0;
}
Now I want to initialize the allocated memory also into the function
void alloc(char **p, int n)
{
*p = new char[n];
for(int i = 0; i<(n - 1); i++)
*p[i] = '1';
*p[n - 1] = '\0';
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
printf("%s", ptr);
return 0;
}
Program crashes. I don’t get why. Please, can someone explain?
Try
(*p)[i]and(*p)[n - 1]instead. The precedence rules cause*p[i]to be evaluated as*(p[i]).