c - 这个 C 矩阵代码有什么作用?

标签 c matrix

<分区>

int matrix[50][100], a, b, c; 
matrix[a][b] = c; 

我真的不明白这段 C 代码的作用,我需要这样做才能将其“翻译”成汇编程序

最佳答案

int matrix[50][100], a, b, c; 
matrix[a][b] = c;

它创建 50 个 100 个 int 的数组。然后它用值 c 初始化第 a 数组的第 b 个整数。但是你应该初始化abc。否则,由于它们具有自动存储期限,因此它们的值将是未定义的。

int matrix[50][100];
int a = 2;
int b = 3;
int c = 4;
matrix[a][b] = c;

这就是我的 gcc (4.4.4) 将代码转换为汇编(AT&T 语法)的方式:

movl    $2, -4(%ebp)                # a = 2
movl    $3, -8(%ebp)                # b = 3
movl    $4, -12(%ebp)               # c = 4
movl    -4(%ebp), %edx              # %edx = a = 2
movl    -8(%ebp), %eax              # %eax = b = 3
imull   $100, %edx, %edx            # %edx = 100 * a = 100 * 2 = 200
addl    %eax, %edx                  # %edx = %edx + b = 200 + 3 = 203
                                    # Formula: %edx = 100 * a + b
movl    -12(%ebp), %eax             # %eax = c = 4
movl    %eax, -20012(%ebp,%edx,4)   # Access to 203-th element (each of these
                                    # are 4 bytes, ie. sizeof(int) on my 
                                    # computer) and put %eax = 4 in it.

在C语言中,数组确实存储在row-major order中.也就是说,在您的源代码中编写 matrix[a][b] 时,您将访问:

offset = row*NUMCOLS + column = a*100 + b

这就是汇编代码显示的内容。

关于c - 这个 C 矩阵代码有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15188395/

相关文章:

c - 将 GSL 数组传递给其他函数

performance - 在每个给定区域找到最小值的有效方法

c++ - 写入多个文件描述符

python - 使用 SciPy 对带状稀疏矩阵进行矩阵求逆

R 内存管理/无法分配大小为 n Mb 的向量

c中 "auto"关键字的概念

R矩阵包: Meaning of the attributes in the dgCMatrix class for sparse matrices

c - scanf() 格式字符串中尾随空格有何影响?

c - 如何从 C 静态库中分离调试符号,然后将其加载到 GDB 中

c - 如何在 C 中使用 getopt 和多个命令打印一次输出