0
Original code (using array of structure):
在此代码中,我将t
作为用户的输入并声明大小为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;
}
What I have tried:
这里代替声明的大小吨结构的阵列,我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;
}
Question:
为什么第二个代码不起作用?需要做什么修正,在第二个代码中,我是否正确使用了malloc
?,是否malloc
在正确的位置?或者是否有语法错误或逻辑错误?
您每次都在循环中分配一个新数组,而'tc'变量对于循环体是局部的,所以它不能在下一个循环中访问。在循环之前分配一次。 – Barmar
为什么你认为你需要首先动态分配它?原始版本有什么问题? – Barmar
当调用堆内存分配函数(malloc,calloc,realloc)时,总是检查(!= NULL)返回的值以确保操作成功 – user3629249