2017-01-16 15 views
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は正しく配置されていますか?または任意の構文エラーまたは論理エラーがありますか?

+2

ループを使用するたびに新しい配列を割り当て、 'tc'変数はループ本体にローカルなので、次のループではアクセスできません。ループの前に一度割り当てます。 – Barmar

+1

なぜ最初に動的に割り当てる必要があると思いますか?元のバージョンで何が間違っていたのですか? – Barmar

+1

ヒープメモリ割り当て関数(malloc、calloc、realloc)のいずれかを呼び出すときに、操作が成功したことを確認するために返された値を常にチェックする(!= NULL) – user3629249

答えて

2

struct testcaseの配列を動的に割り当てる必要があるため、ループに入る前に一度だけ行う必要があります。

struct testcase *tc = malloc(t * sizeof(struct testcase)); 
if (!tc) { 
    perror("malloc failed"); 
    exit(1); 
} 

for(i=0;i<t;i++) 
... 
関連する問題