我怎样才能使以下工作?这个想法是让函数分配一个外部指针,这样我就可以在另一个程序中使用这个概念,但我不能这样做,因为 gcc 一直告诉我参数来自不兼容的指针类型......应该很简单,但我没有看到它。
#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;
}