原始代码(使用结构数组):
在这段代码中,我将 t
作为用户的输入并声明一个结构数组 tc
大小为 t
,然后进行一些处理。
#include<stdio.h>
int main()
{
int t,i,j,k,min=0;
//# of test cases
scanf("%d",&t);
struct testcase
{
int sizeOfArray;
int a[10];
int b[10];
int ans;
};
struct testcase tc[t]; //declaring array of structures, size t
for(i=0;i<t;i++)
{
scanf("%d",&tc[i].sizeOfArray); //entering size of a and b
for(j=0;j<tc[i].sizeOfArray;j++) //entering elements of a
scanf("%d",&(tc[i].a[j]));
for(j=0;j<tc[i].sizeOfArray;j++) //entering elements of b
scanf("%d",&tc[i].b[j]);
}
int no=0;
for(k=0;k<t;k++)
{
min= tc[k].a[0]+tc[k].b[1];
for(i=0;i<tc[k].sizeOfArray;i++)
{
for(j=0;(j<tc[k].sizeOfArray);j++)
{
if((tc[k].a[i]+tc[k].b[j]<min)&&(j!=i))
min=tc[k].a[i]+tc[k].b[j];
}
}
tc[k].ans=min;
printf("%d\n",min);
}
return 0;
}
我尝试过的:
这里我没有声明大小为 t 的结构数组,而是在 for 循环中动态分配结构内存并进行相同的处理。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int t,i,j,k,min=0;
//# of test cases
scanf("%d",&t);
struct testcase
{
int sizeOfArray;
int a[10];
int b[10];
int ans;
};
struct testcase *tc = NULL;
for(i=0;i<t;i++)
{
struct testcase* tc = malloc(20 * sizeof(*tc));
scanf("%d",&tc[i].sizeOfArray); //entering size of a and b
for(j=0;j<tc[i].sizeOfArray;j++) //entering elements of a
scanf("%d",&(tc[i].a[j]));
for(j=0;j<tc[i].sizeOfArray;j++) //entering elements of b
scanf("%d",&tc[i].b[j]);
}
int no=0;
for(k=0;k<t;k++)
{
min=tc[k].a[0]+tc[k].b[1];
for(i=0;i<tc[k].sizeOfArray;i++)
{
for(j=0;(j<tc[k].sizeOfArray);j++)
{
if((tc[k].a[i]+tc[k].b[j]<min)&&(j!=i))
min=tc[k].a[i]+tc[k].b[j];
}
}
tc[k].ans=min;
printf("%d\n",min);
}
return 0;
}
问题:
为什么第二个代码不起作用?需要做哪些更正,在第二个代码中,我是否正确使用了 malloc
?malloc
是否正确放置?或有任何语法错误或逻辑错误吗?
最佳答案
你需要动态分配一个struct testcase
数组,所以你只需要在进入循环之前做一次。
struct testcase *tc = malloc( t * sizeof(struct testcase));
if (!tc) {
perror("malloc failed");
exit(1);
}
for(i=0;i<t;i++)
...
关于c - 在循环中动态分配结构内存 t 次而不是声明结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683146/