Create 2D array from existing 1D arrays in C? -
in perl can create 1d arrays , create 2d array them, following way:
@a1=(a,b,c) @a2=(d,e,f) @a3=(g,h,i) @m23_v1=(\@a1,\@a2,\@a3) here way (assuming @a1, @a2 , @a3 same in previous example):
@m23_v2=([@a1],[@a2],[@a3]) the difference between 2 ways when backslashes used changing $a[0][0] change $a1[0]. on other hand when brackets used value copied changing $a[0][0] not change $a1[0]. bellow memory addresses of variables should clarify mean:
print \$a1[0] scalar(0x2006c0a0) print \$m23_v1[0][0] scalar(0x2006c0a0) print \$m23_v2[0][0] scalar(0x2030a7e8) how achieve same 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 gives me following compilation warnings:
2d.c: in function ‘main’: 2d.c:4:3: warning: initialization makes integer pointer without cast [enabled default] 2d.c:4:3: warning: (near initialization ‘m23[0][0]’) [enabled default] 2d.c:4:3: warning: initialization makes integer pointer without cast [enabled default] 2d.c:4:3: warning: (near initialization ‘m23[0][1]’) [enabled default] 2d.c:5:3: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled default] after execution c code returns following:
1 -1077371888 questions:
- why compilation warnings , how modify code rid of them?
- if given c equivalent backslashed perl version equivalent brackets version (and vice versa)?
- why -1077371888 instead of 1?
you can use array of pointers equivalent of backslahed version (i.e. @m23_v1):
#include <stdio.h> int main(void) { int a1[3] = {1,2,3}; int a2[3] = {4,5,6}; int *m23[2] = {a1, a2}; printf("%d\n", a1[0]); printf("%d\n", m23[0][0]); return 0; } in code:
int m23[2][3] = {a1, a2}; initializer expects filled integers. create two-dimensional array 2 integers: a1, a2. remaining elements initialized zeros. illustrate it, looks like:
int m23[2][3] = {0xaaee33, 0xaaee55, 0, 0, 0, 0}; which same as:
int m23[2][3] = {{0xaaee33, 0xaaee55, 0}, {0, 0, 0}}; // 2 rows, 3 columns however, a1 not integer. it's name of array, implicitely converted int (after converted pointer, points array's first element). in other words implicitely converting addresses of a1 , a2 2 integers. in fact, such operation illegal in c , such code should not compile -pedantic-errors flag (or equivalent).
what equivalent brackets version (and vice versa)?
the equivalent of braced version define multidimensional array of specific size , copy each element of a1 , a2 arrays it:
#include <stdio.h> #include <string.h> int main(void) { int a1[3] = {1,2,3}; int a2[3] = {4,5,6}; int m23[2][3]; memcpy(m23 + 0, a1, sizeof(a1)); memcpy(m23 + 1, a2, sizeof(a2)); printf("%d\n", a1[0]); printf("%d\n", m23[0][0]); return 0; }
Comments
Post a Comment