开发者

Get address of a multidimensional static array

How can I get the address of a multidimensional static array? For example, this is my array

char array[2][10] = {"word1", "word2"};

Is it possible t开发者_如何学运维o get the address to make me reference this array using a pointer like this?

char** pointer;

I tried &array or directly pointer = (char**)array; but it crashes at startup.


char **pointer means that a pointer is pointing to a pointer. So *pointer is expected to be a pointer (e.g. 4-byte value which can be interpreted as an address).

This is not the case with your array: it is a contiguous area in memory (20 bytes).

So when you try to convert the array to char ** your application crashes. It's not possible to do this conversion, char ** must point at a pointer.


"array" is the address of the array in memory but it is not a char**. While you can cast it, the application will crash if you try

printf("%s", pointer[1]);

because in your case is probably the same as

printf("%s", (char *)(0x00000031));

since pointer[1] means "the second 4 byte pointer (assuming x86) starting from 'array'". pointer[0] MAY not crash but won't show "word1" either for the same reason.

You probably want (this is hard to remeber so i had to check online, hope it is correct):

char (*pointer)[10] = array;

Which is a pointer to an array of 10 chars. And if you use pointer[1] it now means "the second 10 chars block starting from 'array'".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜