0
Original code (using array of structure):
このコードでは、ユーザからの入力として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:
ここ 代わりのサイズ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;
}
Question:
なぜ2番目のコードが機能しないのですか? 2番目のコードでは、どのような修正を行う必要がありますか?malloc
を正しく使用しましたか?malloc
は正しく配置されていますか?または任意の構文エラーまたは論理エラーがありますか?
ループを使用するたびに新しい配列を割り当て、 'tc'変数はループ本体にローカルなので、次のループではアクセスできません。ループの前に一度割り当てます。 – Barmar
なぜ最初に動的に割り当てる必要があると思いますか?元のバージョンで何が間違っていたのですか? – Barmar
ヒープメモリ割り当て関数(malloc、calloc、realloc)のいずれかを呼び出すときに、操作が成功したことを確認するために返された値を常にチェックする(!= NULL) – user3629249