gpt4 book ai didi

C:将具有数组的指针传递给函数时,会出现运行时错误。为什么?

转载 作者:行者123 更新时间:2023-11-30 14:41:38 24 4
gpt4 key购买 nike

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 个 header 和 add_up(*p, 5) 并删除 *

关于C:将具有数组的指针传递给函数时,会出现运行时错误。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com