我在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;
}
您正在错误地调用read()
,而write()
不正确 - 您不应该接受已经指向的地址。
更改:
read(&a);
write(&a);
to:
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.
看一下:
#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);
}
我想要什么?如果是这样,请享受。