gpt4 book ai didi

c - 为什么这不会打印?

转载 作者:行者123 更新时间:2023-11-30 19:16:53 24 4
gpt4 key购买 nike

在您觉得有必要将此帖子标记为重复帖子之前,请不要这样做。我已经阅读了我能找到的所有关于指针、数组和函数的主题,但几乎所有主题都太先进了,对我没有任何帮助。

我没有收到错误,但是我的代码不会打印我的数组。看来这里的问题是使用 scanf 。我不认为输入的值实际上被放入 main() 中的数组中。我尝试过使用指针,但每当我尝试使用 scanf 收集用户输入的值并将其放入数组时,都会收到错误“Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)”。

我正在做的工作仅限于在 main() 函数中声明我的数组,但所有操作都将在promptData() 函数中执行。任何帮助都会很棒,我正试图自己解决这个问题。

#import <stdio.h>

void promptData(double data[], int numElem);

int main(int argc, const char * argv[])
{
int size, i;
double array[size];


promptData(array, size);

for (i = 0; i < size; i++)
printf("%.2lf\n", array[i]);

return 0;
}

void promptData(double data[], int numElem)
{
int i;

printf("Enter integer values for size of array.\n");
scanf("%i", &numElem);

for (i = 0; i < numElem; i++)
{
printf("Enter array values.\n");
scanf("%lf", &data[i]);
}
}

最佳答案

您的程序具有未定义的行为,因为变量大小未初始化并且具有不确定的值。

您应该首先在 main 中要求用户输入数组的大小,然后定义数组本身,然后才用值填充它。

例如

int main(int argc, const char * argv[])
{
int size = 0;

printf( "Enter a positive integer value for the size of the array: ");
scanf( "%i", &size);

if ( size == 0 ) exit( 1 );

double array[size];

promptData(array, size);

//...

此外,在 C 中没有这样的指令

#import <stdio.h>

使用代替

#include <stdio.h>

关于c - 为什么这不会打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29192087/

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