以下代码是否可以接受。也就是说,这是做 malloc 的正确方法吗?
这是我可以为我的情况工作的最少代码。我认为这是“正确的方法”,但我对 C 语言非常陌生,总体上没有太多线索。我阅读了几篇相关的 SO 帖子,但似乎没有一个完全符合这种情况。评论?
#include <stdio.h>
// example of calling a function that creates a dynamically sized array and
// returns it to a caller that doesn't know or care about the size of the array
char* return_char_array(){
// for the sake of the example, we determined the size to be 100
char *f=malloc(100*sizeof(char));
// stick something in the first couple of elements for test purposes
*f=65;
*(f+1)=66;
return f;
}
int main(){
// we want this function to remain ignorant of the size or other workings
// of the array, so, no '[]' or 'malloc'
char *wipc = return_char_array();
// well i guess it cares a little, because we assume there are at least 2 elements...
printf("%c,%c\n",*(wipc),*(wipc+1));
system("PAUSE");
return 0;
}