簡體   English   中英

在 C 中打印同一個 Struct 變量的不同值

[英]Printing different values for the same Struct variable in C

#define MAX_HEIGHT 512
#define MAX_WIDTH 512

typedef struct
{
  int lines;
  int cols;
  int highestValue;
  int matrix[MAX_WIDTH][MAX_HEIGHT];
} Pgm;

void getInfo()
{
  Pgm pgm;
  FILE *f = fopen("pepper.pgm", "r");
  bool keepReading = true;
  int line = 0, countSpaces = 0, i = 0;
  do
  {
    fgets(buffer, MAX_LINE, f);
    if (feof(f))
    {
      printf("\nCheguei no final do arquivo");
      keepReading = false;
      break;
    }
    if (line >= 3)
    {
      char *values = strtok(buffer, " ");
      while (values != NULL)
      {
        total++;
        // printf("values: %d, cols: %d, pgm.matrix[%d][%d], total: %d\n", atoi(values), pgm.cols, i, countSpaces, total);
        pgm.matrix[i][countSpaces] = atoi(values);
        if (i == pgm.lines && countSpaces == pgm.cols)
          break;
        countSpaces++;
        if (countSpaces == pgm.cols)
        {
          countSpaces = 0;
          i++;
        }
        values = strtok(NULL, " ");
      }
    }
    line++;
  } while (keepReading);
  fclose(f);
printf("cols: %d, lines: %d, highest: %d, matrix[0][0]: %d", pgm.cols, pgm.lines, pgm.highestValue, pgm.matrix[0][0]);
}

void resolveMatrix()
{
  Pgm pgm;
  printf("cols: %d, lines: %d, highest: %d", pgm.cols, pgm.lines, pgm.highestValue);
}

我有這個getInfo function 讀取.pgm文件並將此文件內的值添加到我的struct內的matrix 當我在這樣的 function 中執行 printf 語句時,它會打印出我想要的正確值。 但是當我嘗試在另一個 function 中執行此操作時,它會打印出不同的值。 我認為這與 memory 地址有關,但我將如何解決這個問題:(

在您的resolveMatrix function 中,您使用的是 struct pgm而未對其進行初始化,因此它將打印在創建結構之前位於堆棧上 memory 位置的隨機垃圾。

如果要使用在其他地方創建的結構,請將指向它的指針作為 function 參數傳遞:

void resolveMatrix(Pgm *pgm)
{
    printf("cols: %d, lines: %d, highest: %d", pgm->cols, pgm->lines, pgm->highestValue);
}

用法:

Pgm pgm;

// Initialize struct fields here ...

resolveMatrix(&pgm);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM