我想使用一个函数来接收一个指向数组的指针及其大小,并将所有元素值设置为零。
但是在函数中检查了数组的值,该值不是1234,如果正确则应该是1234,因为输入值是1234.
只想知道以下代码中的错误在哪里。
#include <stdio.h>
#include <stdlib.h>
void receive(int *point, const int size);
int main(void) {
int a;
int *b;
scanf("%d", &a);
b=(int*)malloc(sizeof(int)*a);
printf("size of input: %d\n", sizeof(b));
receive(b, sizeof(b));
free(b);
return 0;
}
void receive(int *point, const int size) {
int c=sizeof(*point);
printf("filling the array to zero");
int i;
for (i=0; i<c; i++) {
printf("\n previous_value:%d\n", point[i]);
point[i]=0;
printf(", current_value %d\n", point[i]);
}
}
答案 0 :(得分:1)
我更改了一些不正确的语句,结果代码为:
#include <stdio.h>
#include <stdlib.h>
void receive(int *point, const int size);
int main(void) {
int a;
int *b;
scanf("%d", &a);
b= malloc(sizeof(int)*a); //removed implicit declaration of malloc return value
printf("size of input: %d\n", a);
receive(b, a); //changed sizeof(b) to a as second argument of function
free(b);
return 0;
}
void receive(int *point, const int size) {
//removed int c = sizeof(*point); unnecessary statement
printf("filling the array to zero");
int i;
for (i=0; i<size; i++) { //substituted c with size
printf("\n previous_value:%d\n", point[i]);
point[i]=0;
printf(", current_value %d\n", point[i]);
}
}