struct instruction {
int value;
};
int n; // Number of instructions
struct instruction **instructions; //Required to use ** and dynamic array
說我想存儲n個指令並在每條指令中存儲一個值。 我該怎麼做**說明? 所以我希望能夠稍後從特定的指令中調用一個值。C指針指針問題
非常感謝
到目前爲止,我嘗試了這些,一些scanfs和動態數組創建。 所以它需要計數器的數量,然後需要線程數(pthreads),然後在每個線程內需要多少條指令。我正試圖找到一種方法來在每個線程中存儲指令。 **結構給出
int
main(void) {
scanf(" %d", &ncounters); //Ask for number of counters
int i;
if(counters = malloc(sizeof(struct counter)*ncounters)){
for(i=0; i < ncounters ;i++){
counters[i].counter = 0;
}
}
scanf(" %d", &nthreads); //Ask for number of threads
if(ninstructions = (int*) malloc(nthreads*sizeof(int))){
for(i=0; i < nthreads ;i++){
ninstructions[i] = 0;
}
}
for(i=0; i < nthreads ;i++){
scanf(" %d", &ninstructions[i]); //Ask for number of instructions within threads[i]
// Things got messy from here ...
instructions = malloc(sizeof(struct instruction*)*ninstructions[i]);
for(int j=0; j < ninstructions[j] ;j++){
instructions[j] = malloc(sizeof(struct instruction));
int x;
printf("Enter rep for thread %d inst %d.\n",i+1 ,j+1);
scanf(" %d", &x);
instructions[i][j].repetitions = x;
}
}
printf(" Instruction x: %d.\n", instructions[0][0].repetitions);
//=============================================================================
// Just testing with printf
printf("Number of counters: %d.\n", ncounters);
printf("Number of threads: %d.\n", nthreads);
for(i=0; i < nthreads; i++){
printf("Thread %d has %d instructions.\n", i+1, ninstructions[i]);
}
//=============================================================================
free(instructions);
free(ninstructions);
free(counters);
return 0;
}
我終於得到了一些進展,但在指令存儲部分出現分段錯誤。
struct counter *counters;
struct instruction{
struct counter *counter;
int repetitions;
void (*work_fn)(long long*);
};
for(i=0; i < nthreads ;i++){
scanf(" %d", &ninstructions[i]); //Ask for number of instructions within threads[i]
instructions = malloc(nthreads*sizeof(struct instruction *));
instructions[i] = malloc(ninstructions[i]*sizeof(struct instruction));
for(int j=0;j < ninstructions[i] ;j++){
int Srepetition;
char Sfunction;
int Scounter;
scanf(" %d %c %d", &Scounter, &Sfunction, &Srepetition);
//Problem seems to be here "Segmentation fault" ..............
instructions[i][j].repetitions = Srepetition;
instructions[i][j].counter = (counters+Scounter);
if(Sfunction == 'I'){
instructions[i][j].work_fn(&increment);
}else if(Sfunction == 'D'){
instructions[i][j].work_fn(&decrement);
}else if(Sfunction == '2'){
instructions[i][j].work_fn(&mult2);
}else{
printf("error\n");
}
printf("Thread: %d Instruction: %d.\n", i+1, j+1);
}
}
家庭作業? (對於愚蠢愚蠢愚蠢STUPID最小注釋長度的額外字符) – 2011-04-28 20:36:19
爲什麼這是必需的雙指針?我認爲這不是必要的。你可以說得更詳細點嗎?你可以告訴玩具試過了什麼(: – 2011-04-28 20:39:23
聽起來像是作業(或者是一本書的練習),如果是這樣,你應該給它加上標籤,因此我們知道給你什麼樣的答案 – jalf 2011-04-28 20:41:07