Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this C matrix code do? [closed]

Tags:

c

matrix

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

I really dont understand what this C code does, and I need to do that so I can "translate it" into assembler

like image 530
Folke Avatar asked Sep 20 '26 13:09

Folke


1 Answers

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

It creates 50 arrays of 100 int. Then it initialize the bth integer of the ath array with the value c. But you shall initialize a, b and c. Otherwise, since they have automatic storage duration, their values will be undefined.

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

This is how my gcc (4.4.4) turns the code into assembly (AT&T syntax):

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.

In C, arrays are indeed stored in row-major order. That is, when writing matrix[a][b] in your source code, you will access to:

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

That's what the assembly code shows.

like image 78
md5 Avatar answered Sep 22 '26 09:09

md5