gpt4 book ai didi

c - 读取大小无效 - 查找命令行平均值

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:48 24 4
gpt4 key购买 nike

我试图找到在命令行执行期间添加的所有数字的平均值。我收到一些 improoer 内存分配的 valgrind 错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int * arg2int(int argc, const char* argv[]) {
int i = 1;
int *result = malloc (sizeof (int) * (argc-1));
for (i = 1; i < argc; i++){
result[i] = atoi(argv[i]);
}
return result;
}

float arrayAvg(int size, int *array) {
/*STUB return 0.0/0.0; */
int i = 0;
float sum = 0.0f;
for (i = 0; i <= size; i++)
sum = sum + array[i];
int avg = sum/size;
return (float)avg;
}
int main(int argc, const char* argv[]) {
int *array = arg2int(argc, argv);
float avg = arrayAvg(argc-1, array);
printf("%.2f\n",avg);
return 0;
}

这是 Valgrind 错误,

==785== Memcheck, a memory error detector
==785== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==785== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==785== Command: ./out
==785==
==785== Invalid read of size 4

我分析说我正在从命令行条目的常量字符数组读取到整数数组。但是如何删除 valgrind 错误。快速笔记该程序将正确执行而不会出现任何错误。我已经测试过了。这只是为了理解为什么 valgrind 错误会增加。

示例输出:

$ ./out 4 6 
5.00

最佳答案

你有两个错误:在@BLUEPIXY 已经提到的 arg2int 中

result[i] = atoi(argv[i]); --> result[i-1] = atoi(argv[i]);

并且在 arrayAvg 中正如@amdixon 所说

for (i = 0; i <= size; i++) --> for (i = 0; i < size; i++)

现在看起来像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int * arg2int(int argc, const char* argv[]) {
int i = 1;
int *result = (int*)malloc (sizeof (int) * (argc-1));

for (i = 1; i < argc; i++)
result[i-1] = atoi(argv[i]);

return result;
}

float arrayAvg(int size, int *array)
{
int i = 0;
float sum = 0.0f;

for (i = 0; i < size; i++)
sum = sum + array[i];

return sum/size;
}
int main(int argc, const char* argv[])
{
int *array = arg2int(argc, argv);
float avg = arrayAvg(argc-1, array);
printf("%.2f\n",avg);

return 0;
}

关于c - 读取大小无效 - 查找命令行平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845705/

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