С Указатель Указатель Вопрос - PullRequest
2 голосов
/ 29 апреля 2011
struct instruction {
   int value;
};

int n; // Number of instructions

struct instruction **instructions; //Required to use ** and dynamic array

Скажем, я хочу сохранить n инструкций и сохранить значение в каждой инструкции. Как бы я сделал это с ** инструкциями? Поэтому я хочу иметь возможность вызывать значение из определенной инструкции позже.

Большое спасибо

Пока что я попробовал это, несколько 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);
    }
}

1 Ответ

2 голосов
/ 29 апреля 2011

Достаточно всего одного * для создания динамического массива, с ** вы будете создавать матрицу.

struct instruction *instructions = malloc(n * sizeof(struct instruction));

/* setting some random values */
for (int i=0;i<n;i++)
     instructions[i]->value = i;

/* accessing values */
for (int i=0;i<n;i++)
     printf("instruction %d value %d\n",i,instructions[i]->value);

/* don't forget to free */
free(instructions);

Пожалуйста, ищите ссылки о dynamic arrays in C, чтобы узнать больше. Например, этот

1012 * редактировать *

... если вам действительно нужна матрица, это эквивалентный код:

int n,z; // for number cols and rows

struct instruction **instructions = malloc(n * sizeof(struct instruction *));

/* setting some random values */
for (int i=0;i<n;i++) {
     instructions[i] = malloc(z * sizeof(struct instruction));
     for (int j=0;j<z;j++) 
         instructions[i][j]->value = i * j;
}
/* accessing values */
for (int i=0;i<n;i++) {
     for (int j=0;j<z;j++) 
          printf("instruction %d,%d value %d\n",i,j,instructions[i][j]->value);
}

/* don't forget to free */ 
for (int i=0;i<n;i++)
     free(instructions[i]);
free(instructions);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...