【发布时间】:2012-07-04 14:30:59
【问题描述】:
以下代码是否可接受。也就是说,这是做 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;
}
【问题讨论】:
-
你有什么问题?
-
如果这是作业添加作业标签
-
'这是完成调用创建并返回动态大小数组的函数的正确方法'?
-
从某种意义上说,这并不是真正的家庭作业,因为我没有参加课程或类似的课程。
-
你的评论说
no '[]',但是你使用*(wipc+1),和wipc[1]完全一样。