【发布时间】:2021-04-07 06:57:58
【问题描述】:
我尝试在 C 中实现矩阵结构(生成并显示)。我对生成没有问题,但我发现了一些我不明白的东西。当我取消注释 printf("\n") 时,我没有从矩阵中获取变量,但是注释 printf("\n") 一切正常。这不是一个大问题,但我很好奇为什么会发生这种情况。看起来 printf 破坏了我的结构。
void show_matrix(struct matrix matrix1){
for(int i =0; i < matrix1.number_of_row; i++){
for(int j = 0; j <matrix1.number_of_columns; j++){
printf("%d " , matrix1.variable[i * matrix1.number_of_columns + j]);
}
// printf("\n");
}
}
这是我的主要内容:
#include <stdio.h>
#include "matrix_operations.h"
int main(){
int columns;
int rows;
printf("Enter the number of columns \n");
scanf("%d",&columns);
printf("Enter the number of rows \n");
scanf("%d", &rows);
struct matrix matrix1;
matrix1 = generate_matrix(columns,rows);
show_matrix(matrix1);
return 0;
}
这是我的文件 matrix_operations.h:
#include "matrix.h"
#include <stdlib.h>
struct matrix generate_matrix(int columns, int rows){
int value;
struct matrix matrix1;
matrix1.number_of_columns = columns;
matrix1.number_of_row = rows;
int values[rows * columns];
matrix1.variable = values;
for(int i = 0 ; i < rows ; i++){
for(int j =0 ; j <columns ; j++){
value = random() %2;
matrix1.variable[i * columns +j] = value;
/* Uncomment to see generated matrix
printf("%d ", matrix1.values[ i * columns +j]);
*/
}
/* Uncomment to see generated matrix
printf("\n");
*/
}
return matrix1;
}
void show_matrix(struct matrix matrix1){
for(int i =0; i < matrix1.number_of_row; i++){
for(int j = 0; j <matrix1.number_of_columns; j++){
printf("%d " , matrix1.variable[i * matrix1.number_of_columns + j]);
}
/* Uncomment to not working correctly
printf("\n");
*/
}
}
这是我在文件 matrix.h 中的结构:
struct matrix{
int number_of_columns;
int number_of_row;
int *variable;
};
示例输入:
4
4
带有注释 printf 的示例输出(16 个随机数 0 或 1):
1 0 1 1 0 0 1 1 0 0 1 1 0 1 0 1
带有未注释 printf 的示例输出
1 0 1 1
-2051332800 32571 0 0
0 0 -2053095405 32571
-2051684704 32571 10 0
【问题讨论】:
-
标准输出是“缓冲的”。刷新它需要某些事件 - 例如打印新行。
-
但问题是反过来的:在输出换行符时不起作用。
-
...这种奇怪现象可能是代码中其他地方未定义行为的症状。
-
@Cebul 由于您的问题缺少大部分代码,您介意在评论
printf("\n");之前和评论此类行之后包含输出吗? -
哦,我完全是倒着读的。我看不出添加
printf会如何导致问题。请创建一个minimal reproducible example。
标签: arrays c matrix struct printf