我正在努力使用calloc和realloc进行数组初始化.我正在尝试编写一个程序,它使用fork()和一个伴随程序从命令行参数计算最终总和.
如果我从命令行收到一组奇数整数,例如:./ program 1 2 3 4 5.
它应该看到数量是奇数并将我的输入数组初始化为6个点并在最后一个点放置零.如下:[0] = 1,[1] = 2,[2] = 3,[3] = 4,[4] = 5,[5] = 0.这样我的同伴程序就能做到了计算.
如果我从命令行接收偶数量的整数,例如:./ program 1 2 3 4.它将执行与上面相同的操作,除非没有零,因为整数集是偶数.
输出数组应初始化为整数除以2的数量.因此,如果我有6个参数,它将被初始化为3.如果我收到奇数的整数,如7,它将重新分配输入数组并放入最后的零,从而产生整数8.因此它将它除以2并使输出初始化为4.
我的输出数组最终会保存每对数字的总和.所以上面就是这样.
1 + 2 = 3,3 + 4 = 7,5 + 0 = 5.
然后输出数组将保持[3],[7],[5].然后循环将从那继续并从剩余的参数计算最终总和.
我无法理解这一点,因为我的数组没有正确初始化,如果参数数为奇数,则将零添加到输入数组.
请参阅以下代码:
#include <stdio.h> /* printf, stderr, fprintf */
#include <unistd.h> /* _exit, fork */
#include <stdlib.h> /* exit */
#include <errno.h> /* errno */
#include <sys/wait.h>
int main(int argc, char** argv)
{
int size = argc - 1;
int* input;
int* output;
int calc;
if(size == 1 && size % 2 != 0)
size++;
if(size % 2 != 0)
{
calc = (size+1)/2;
input = (int*)realloc(NULL,(argc));
output = (int*)calloc(calc, sizeof(int));
int j;
for(j = 1; j < argc; j++)
{
input[j-1] = atoi(argv[j]);
}
input[argc] = 0;
}
else
{
calc = (size)/2;
input = (int*)realloc(NULL,(size));
output = (int*)calloc(calc, sizeof(int));
int j;
for(j = 1; j < argc; j++)
{
input[j-1] = atoi(argv[j]);
}
}
int i;
for(i = 0; i < argc; i++)
printf("input[%d]: %d\n",i,input[i]);
free(input);
free(output);
exit(0)
}
Run Code Online (Sandbox Code Playgroud)
realloc以字节为单位获取分配大小,而不是数组元素,所以你需要像这样乘以sizeof(int)
input = (int*)realloc(NULL,(argc) * sizeof(int));
output = (int*)calloc(calc, sizeof(int));
Run Code Online (Sandbox Code Playgroud)
这也不起作用
input = (int*)realloc(NULL,(argc) * sizeof(int));
...
input[argc] = 0;
Run Code Online (Sandbox Code Playgroud)
如果输入被分配给持有argc整数,那么最大允许的索引input是input[argc-1].我不清楚你是分配太少的项目,还是输入[argc]是错误的.
编辑:我可能会建议将其作为替代配方.如果我们在解析输入之前将输入数组中的最后一个槽设置为0 ,那么我们不关心输入的数量是偶数还是奇数.
int calc = argc/2; // actually (argc-1+1)/2
int * input = (int *)realloc(NULL, (calc*2) * sizeof(int));
int * ouput = (int *)calloc(calc, sizeof(int));
input[calc*2 - 1] = 0; // in case we run out of inputs
for (int j = 1; j < argc; ++j)
{
input[j-1] = atoi(argv[j]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4134 次 |
| 最近记录: |