0

これは、C でコンパイルしている私のコードです。現在、構造体 (構造体命令) の配列であるグローバル変数「コード」があります。代わりに、これをメインのローカル変数にして、パラメーターとして渡そうとしています。また、これは、ファイルを読み取って構造体命令を返す必要があることを意味すると思います*。誰かが説明してくれたり、「コード」をローカル変数として適切に使用する方法を教えてくれたりすると、とてもありがたいです。また、ローカル変数がグローバル変数よりも優れている、または効率的である理由にも興味があります。ありがとう!

#include<stdio.h>
#include <stdlib.h>


typedef struct instruction{
 int op; //opcode
 int  l; // L
 int  m; // M
} instr;

FILE * ifp; //input file pointer
FILE * ofp; //output file pointer
instr code[501];

void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);


int main(){

 read_file(code);
 print_input_list(code);//used for debugging
 print_program(code);

}

void read_file(instr code[]){
 int i = 0;

 ifp = fopen("input.txt", "r");

 while(!feof(ifp)){
    fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
    i++;
 }
 code[i].op = -1; //identifies the end of the code in the array
 fclose(ifp);
}
4

3 に答える 3

0

宣言を必要とする関数内に宣言を移動する必要があります。

#include <stdio.h>
#include <stdlib.h>


typedef struct instruction{
 int op; //opcode
 int  l; // L
 int  m; // M
} instr;

void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);


int main(){

  instr code[501];  // code[] declaration moved HERE!!!!

 read_file(code);
 print_input_list(code);//used for debugging
 print_program(code);

}

void read_file(instr code[]){
 int i = 0;

 FILE * ifp; //ifp FILE* declaration moved HERE!!!!

 ifp = fopen("input.txt", "r");

 while(!feof(ifp)){
    fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
    i++;
 }
 code[i].op = -1; //identifies the end of the code in the array
 fclose(ifp);
}

ifp宣言を内側readfile()code内側に移動しましmain()た。変数ofpは使用されていないため、削除されました。
別の関数内で使用している場合はofp、そこで宣言します。

于 2013-09-12T18:50:37.733 に答える
0

十分に単純です。現在コーディングしているため、効率に実際の変化はありません。唯一の変更点は、コードのストレージがスタックからのものになることです

int main(){ 
 instr code[501];

 read_file(code);
 print_input_list(code);//used for debugging
 print_program(code);
}
于 2013-09-12T18:50:45.783 に答える
0

先に進み、質問の最後の部分に答えようとします。

また、ローカル変数がグローバル変数よりも優れている、または効率的である理由にも興味があります。

ローカル定義変数とグローバル定義変数にはいくつかの違いがあります。

  1. 初期化。グローバル変数は常にゼロに初期化されますが、ローカル変数は割り当てられる前に未指定/不確定の値を持ちます。前述のように初期化する必要はありません。
  2. スコープ。グローバル変数は、ファイル内の任意の関数からアクセスできます (またextern、参照を渡さずに、を使用してファイルからアクセスすることもできます。したがって、この例では、コードへの参照を関数に渡す必要はありません。関数ローカル変数は、現在のブロックでのみ定義されます。

例えば:

int main() {
  int j = 0;
  {
    int i = 0;
    printf("%d %d",i,j); /* i and j are visible here */
  }
  printf("%d %d",i,j); /* only j is visible here  */
 }

iメイン コード ブロックに表示されなくなったため、これはコンパイルされません。ローカル変数と同じ名前のグローバル変数がある場合、事態は複雑になる可能性があります。許可されていますが、推奨されていません。

編集:コメントに基づいてローカル変数の初期化が変更されます。上記のイタリック体のテキストを変更。

于 2013-09-12T19:04:44.327 に答える