Home > Net >  Printing different values for the same Struct variable in C
Printing different values for the same Struct variable in C

Time:12-03

#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);
}

I have this getInfo function that reads a .pgm file and adds the values inside this file to a matrix inside my struct. When i do a printf statement inside such function it prints out the right values that i want. But when i try to do that inside another function it prints out diffent values. I think this has to do with memory addres, but how would i solve this :(

CodePudding user response:

In your resolveMatrix function you are using the struct pgm without initializing it, so it will print random garbage that was on that memory location on the stack before the struct was created.

If you want to use a struct that was created somewhere else, pass a pointer to it as a function parameter:

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

Usage:

Pgm pgm;

// Initialize struct fields here ...

resolveMatrix(&pgm);
  • Related