C: 将具有数组的指针传递给函数时会出现 运行 时间错误。为什么?
C: On passing pointer having array to a function there is run time error. Why?
int add_up (int *a, int num_elements);
int main()
{
int orders[5] = {100, 220, 37, 16, 98};
int *p;
p=&orders[0];
printf("Total orders is %d\n", add_up(*p, 5));
here If I pass pointer what is the problem? As pointer will point to no. 100 value. As 100 is an int value which will go to int *a. And the program should go well right?
Edit 1: If I give p here in place of *p then will it be address of orders[0] and not value 100 right?
But function int *a wants value 100 right. Correct me if I am wrong in this concept and thanks.
return 0;
}
int add_up (int *a, int num_elements)
{
int total = 0;
int k;
for (k = 0; k < num_elements; k++)
{
total += a[k];
}
return (total);
}
用以下代码替换您的代码:
#include <stdio.h>
#include <stdlib.h>
int add_up (int *a, int num_elements);
int main()
{
int orders[5] = {100, 220, 37, 16, 98};
int *p;
p=&orders[0];
printf("Total orders is %d\n", add_up(p, 5));
return 0;
}
int add_up (int *a, int num_elements)
{
int total = 0;
int k;
for (k = 0; k < num_elements; k++)
{
total += a[k];
}
return (total);
}
您忘记包含 2 headers 和 add_up(*p, 5)
并删除了 *
。
int add_up (int *a, int num_elements);
int main()
{
int orders[5] = {100, 220, 37, 16, 98};
int *p;
p=&orders[0];
printf("Total orders is %d\n", add_up(*p, 5));
here If I pass pointer what is the problem? As pointer will point to no. 100 value. As 100 is an int value which will go to int *a. And the program should go well right? Edit 1: If I give p here in place of *p then will it be address of orders[0] and not value 100 right? But function int *a wants value 100 right. Correct me if I am wrong in this concept and thanks.
return 0;
}
int add_up (int *a, int num_elements)
{
int total = 0;
int k;
for (k = 0; k < num_elements; k++)
{
total += a[k];
}
return (total);
}
用以下代码替换您的代码:
#include <stdio.h>
#include <stdlib.h>
int add_up (int *a, int num_elements);
int main()
{
int orders[5] = {100, 220, 37, 16, 98};
int *p;
p=&orders[0];
printf("Total orders is %d\n", add_up(p, 5));
return 0;
}
int add_up (int *a, int num_elements)
{
int total = 0;
int k;
for (k = 0; k < num_elements; k++)
{
total += a[k];
}
return (total);
}
您忘记包含 2 headers 和 add_up(*p, 5)
并删除了 *
。