简体   繁体   English

C-在结构数组中打印2d数组的元素

[英]C - Printing elements of a 2d array inside a struct array

Im trying to make a function that sets the values of a 2D array, and then another function that prints those values. 我试图创建一个设置2D数组的值的函数,然后再创建一个打印这些值的函数。

For some reason, with my current implementation, if I create a 3x3 matrix and I set every value to the number 5, it prints the values, but it prints them counting up from 5, so it prints 567, 678, 789, when instead I want it to print the exact value that I set. 出于某种原因,在我当前的实现中,如果我创建一个3x3矩阵并将每个值都设置为数字5,它将打印这些值,但是会打印从5开始计数的值,因此在打印567、678、789时会显示我希望它打印我设置的确切值。

Here are the function definitions - what am I doing wrong?: 这是函数定义-我在做什么错?

Struct Definition: 结构定义:

    struct matrix{
        char matrixName[50];
        int rows;
        int columns;
        float* data;
    };
    typedef struct matrix matrix_t;

Matrix Creation: 矩阵创建:

int create_matrix(matrix_t* matrixP, int matrixLocation){

  char tempName[50];
  int rows, cols;


  printf("Enter a name for your matrix>\n");
  scanf("%s", tempName);

  printf("Enter the number of rows>\n");
  scanf("%d", &rows);

  printf("Enter the number of cols>\n");
  scanf("%d", &cols);

  float * our_matrix = (float *) malloc(rows * cols * sizeof(float));  

  strcpy(matrixP[matrixLocation].matrixName, tempName);
  matrixP[matrixLocation].rows = rows;
  matrixP[matrixLocation].columns = cols;
  matrixP[matrixLocation].data = our_matrix;

  return 0;

}

Set Values: 设定值:

int setValues(matrix_t* our_matrix, int matrix_index) {
  int counter = 0;
  int row = 0, col = 0;
  for (col = 1; col <= our_matrix[matrix_index].columns; col++) {
    for (row = 1; row <= our_matrix[matrix_index].rows; row++) {
      counter++;

      printf("Enter the value for column number %d of row number %d>\n", col, row);
      scanf("%f", our_matrix[matrix_index].data+(col-1)+(row-1));                
    }
    /* separate rows by newlines */
  }
    return 0;
}

Print: 打印:

int printMatrix(matrix_t* our_matrix, int index) {
      int row = 0, col = 0;
      for (col = 1; col <= our_matrix[index].columns; col++) {
        for (row = 1; row <= our_matrix[index].rows; row++) {
      printf(" %2.f ", *our_matrix[index].data+(col-1)+(row-1));   
    }
    printf("\n");
  }
    return 0;
}

If I call the printMatrix() function without first using setValues, it seems to print the relative position of the cell that it's printing like so: 如果我不先使用setValues就调用printMatrix()函数,则看起来像这样打印单元格的相对位置:

在此处输入图片说明

But when I call setValues() and set all values to the number 5, its prints counting up from the number 5 like this: 但是,当我调用setValues()并将所有值设置为数字5时,它的打印从数字5开始递增,如下所示:

在此处输入图片说明

Your position calculation is incorrect. 您的排名计算不正确。 There's one problem and one 'aconventional notation' issue. 有一个问题和一个“常规符号”问题。

The problem is the calculation of the array subscripts: 问题是数组下标的计算:

 scanf("%f", our_matrix[matrix_index].data+(col-1)+(row-1)); printf(" %2.f ", *our_matrix[index].data+(col-1)+(row-1)); 

You need to multiply the (row - 1) value by our_matrix[matrix_index].cols . 您需要将(row - 1)值乘以our_matrix[matrix_index].cols You will probably do better with some shorter names for the values: 使用一些较短的值名称可能会做得更好:

int max_col = our_matrix[matrix_index].columns;
int max_row = our_matrix[matrix_index].rows;
float *data = our_matrix[matrix_index].data;

for (col = 1; col <= max_col; col++)
{
    for (row = 1; row <= max_row; row++)
    {
        printf("Enter the value for column number %d of row number %d>\n", col, row);
        if (scanf("%f", data + (col-1) + (row-1) * max_col) != 1)
        {
            …report error and do not continue…
        }
    }
}

for (col = 1; col <= max_col; col++)
{
    for (row = 1; row <= max_row; row++)
        printf(" %.2f", data[(col-1) + (row-1) * max_col]);
    putchar('\n');
}

That deals with the substantive bug. 那处理了实质性的错误。 Note the error checking on scanf() . 注意scanf()上的错误检查。 That is important in 'real world' programs (even if you get away without it in classes or in online contests). 这在“现实世界”计划中很重要(即使您在课堂上或在线比赛中没有参加该计划也是如此)。 You could sensibly use the notation &data[(col-1) + (row-1) * max_cols] in place of data + (col-1) + (row-1) * max_cols in the call to scanf() too — that would improve the consistency of the code. 您也可以在对scanf()的调用中明智地使用符号&data[(col-1) + (row-1) * max_cols]代替data + (col-1) + (row-1) * max_cols —会提高代码的一致性。

The 'aconventional notation' issue is that in C, array indexing starts at 0, not 1, and you could avoid the multitude of -1 terms by following the C conventions. “常规表示法”的问题是,在C中,数组索引从0而不是1开始,并且您可以通过遵循C约定来避免多个-1项。 This snippet also declares the loop variables when they're needed, minimizing their scope. 该代码段还在需要时声明了循环变量,从而最大程度地减小了范围。 This is a feature of C since C99 — it may not be available to you on some retrograde (but popular and widespread) platforms. 自C99以来,这是C的功能-在某些逆行(但流行且广泛使用)的平台上可能无法使用。

for (int col = 0; col < max_col; col++)
{
    for (int row = 0; row < max_row; row++)
        printf(" %.2f", data[col + row * max_col]);
    putchar('\n');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM