How can I make the following work? The idea is for the function to allocate an external pointer so I can use this concept in another program, but I can’t do that because gcc keeps telling me that the argument is from an incompatible pointer type… It should be simple, but I’m not seeing it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int allocMyPtr(char *textToCopy, char **returnPtr) {
char *ptr=NULL;
int size=strlen(textToCopy)+1;
int count;
ptr=malloc(sizeof(char)*(size));
if(NULL!=ptr) {
for(count=0;count<size;count++) {
ptr[count]=textToCopy[count];
}
*returnPtr = ptr;
return 1;
} else {
return 0;
}
}
int main(void) {
char text[]="Hello World\n";
char *string;
if(allocMyPtr(text,string)) {
strcpy(string,text);
printf(string);
} else {
printf("out of memory\n");
return EXIT_FAILURE;
}
free(string);
return EXIT_SUCCESS;
}
It’s almost correct, but as your function wants a pointer to a pointer, you have to pass the address of the pointer to the function, using the address-of operator: