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