我用C编写了这段代码,读取数字数组然后将它们写入屏幕,但是对于某些n值(例如n = 6),它会产生错误。有什么问题?
#include <stdio.h>
#include <stdlib.h>
int n;
void read(int *a)
{
int i;
for(i=0;i<n;i++) scanf("%d",a+i);
}
void write(int *a)
{
int i;
for(i=0;i<n;i++) printf("%d",*(a+i));
}
int main()
{
int *a;
printf("n=");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
read(&a);
write(&a);
return 0;
}
答案 0 :(得分:2)
您正在错误地调用read()
和write()
- 您不应该使用已经是指针的地址。
变化:
read(&a);
write(&a);
为:
read(a);
write(a);
请注意,将来,您应始终启用编译器警告并注意它们 - 如果已启用编译器警告,则此错误会立即显现:
<stdin>:21:10: warning: incompatible pointer types passing 'int **' to parameter of type 'int *'; remove & [-Wincompatible-pointer-types]
read(&a);
^~
<stdin>:4:16: note: passing argument to parameter 'a' here
void read(int *a)
^
<stdin>:22:11: warning: incompatible pointer types passing 'int **' to parameter of type 'int *'; remove & [-Wincompatible-pointer-types]
write(&a);
^~
<stdin>:9:17: note: passing argument to parameter 'a' here
void write(int *a)
^
2 warnings generated.
答案 1 :(得分:-2)
看看这个:
#include <stdio.h>
int n;
void read(int *a)
{
int i;
for (i = 0; i < n; i++)
{
scanf("%d", (a + i));
// don't forget to consume the rest of line until ENTER
scanf("%*[^\n]"); // consume all caracters until the newline
scanf("%*c"); // consume the newline
}
}
void write(int *a)
{
int i;
for (i = 0; i<n; i++) printf("%d", *(a + i));
}
int main(int argc, char *argv[])
{
int *a;
printf("n= ");
scanf("%d", &n);
// don't forget to consume the rest of line until ENTER
scanf("%*[^\n]"); // consume all caracters until the newline
scanf("%*c"); // consume the newline
a = (int *)malloc(n*sizeof(int));
// this is a FATAL ERROR !
//read(&a);
//write(&a);
read(a);
write(a);
printf("\n");
// don't forget to release memory allocated with 'malloc'
free(a);
return(0);
}
我这就是你想要的?如果是这样,享受吧。