In perl I can create 1D arrays and then create 2D array from them, following way:
@a1=(a,b,c)
@a2=(d,e,f)
@a3=(g,h,i)
@m23_v1=(\@a1,\@a2,\@a3)
Here is another way (assuming that @a1, @a2 and @a3 are the same as in previous example):
@m23_v2=([@a1],[@a2],[@a3])
The difference between those two ways is that when backslashes are used then changing $a[0][0] will also change $a1[0]. On the other hand when brackets are used then the value is copied so changing $a[0][0] will not change $a1[0]. Bellow are memory addresses of variables which should clarify what I mean:
print \$a1[0]
SCALAR(0x2006c0a0)
print \$m23_v1[0][0]
SCALAR(0x2006c0a0)
print \$m23_v2[0][0]
SCALAR(0x2030a7e8)
How to achieve the same but in C? I've tried following code:
# include <stdio.h>
int main(){
int a1[3] = {1,2,3};
int a2[3] = {4,5,6};
int m23[2][3] = {a1, a2};
printf("%d\n", a1[0]);
printf("%d\n", m23[0][0]);
}
But it gives me following compilation warnings:
2d.c: In function ‘main’:
2d.c:4:3: warning: initialization makes integer from pointer without a cast [enabled by default]
2d.c:4:3: warning: (near initialization for ‘m23[0][0]’) [enabled by default]
2d.c:4:3: warning: initialization makes integer from pointer without a cast [enabled by default]
2d.c:4:3: warning: (near initialization for ‘m23[0][1]’) [enabled by default]
2d.c:5:3: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
After execution the C code returns following:
1
-1077371888
Questions:
- Why I get the compilation warnings and how to modify the code to get rid of them?
- If given C is equivalent to backslashed perl version then what is the equivalent for brackets version (and vice versa)?
- Why I get -1077371888 instead of 1?