我已经看到了一些从stackoverflow上的函数返回数组的例子.我按照这些例子,但我仍然收到警告.
#include <stdio.h>
#include <stdlib.h>
char * getNum();
int main(){
int * num;
int * i;
num = getNum();
puts(num);
return 0;
}
char * getNum(){
FILE * fp;
fp = fopen("number", "r"); //getting a 1000 digit number from a file
char * n; //putting it in "array"
n = (char *)malloc(1000 * sizeof(char));
char x[100];
int i, j = 0;
while(!feof(fp)){
fgets(x, 100, fp);
for(i=0; i<50; i++){ //getting the first 50 characters in a line
n[j] = x[i]; //to avoid "new line"
j++;
}
}
fclose(fp);
n[1000] = '\0';
return n;
}
Run Code Online (Sandbox Code Playgroud)
puts(num)如果我忽略警告,给出正确的号码?他们为什么会出现?我希望这不算是重复.
cc 8.c -o 8
8.c: In function ‘main’:
8.c:11:9: warning: assignment from incompatible pointer type
num = getNum();
^
8.c:12:10: warning: passing argument 1 of ‘puts’ from incompatible pointer type
puts(num);
^
In file included from 8.c:1:0:
/usr/include/stdio.h:695:12: note: expected ‘const char *’ but argument is of type ‘int *’
extern int puts (const char *__s);
^
Run Code Online (Sandbox Code Playgroud)
问题是你似乎正在将调用的结果getNum赋给一个类型的变量int *,这在getNum返回a时没有多大意义char *.
您还尝试使用puts该类型的变量进行打印int *,同时puts仅接受a const char *.
更重要的是,你已经超出了函数代码的界限,正如我在评论中已经提到的那样:n = (char *)malloc(1000 * sizeof(char));为1000个字符分配内存.n[1000] = '\0';尝试访问第1001个(!)字符.请记住,数组索引从零开始!
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |