简体   繁体   中英

Using pointers to access 2D array linearly

I'm trying to use pointers to treat a 2D array as a 1D array (since that's the way it is in memory to my understanding). I thought I had it, then I figured out that I was only adding to the ASCII value of 'a' (and printing abcdefghijkl instead of abcghidefjkl).

How can I rewrite my printf statement to print abcghidefjkl? Also, how can I do that with ints and doubles (ie - using data2 and data3)

int main()
{

int i = 0;
char data[4][3] = { {'a','b','c'},{'g','h','i'},{'d','e','f'},{'j','k','l'}};
int data2[4][3] = { {1,2,3},{7,8,9},{4,5,6},{10,11,12}};
double data3[4][3] = { {1,2,3},{7,8,9},{4,5,6},{10,11,12}};

for(i=0;i<12;i++)
{
printf("%c\n", **(data)+i*sizeof(char));
}

return 0;
}

Thanks!

change one line of you code

#include "stdio.h"

    int main()
    {

    int i = 0;
    char data[4][3] = { {'a','b','c'},{'g','h','i'},{'d','e','f'},{'j','k','l'}};
    int data2[4][3] = { {1,2,3},{7,8,9},{4,5,6},{10,11,12}};
    double data3[4][3] = { {1,2,3},{7,8,9},{4,5,6},{10,11,12}};

    for(i=0;i<12;i++)
    {
    printf("%c\n", *(*data +i));   // here is the change
    }

    return 0;
    }

Yes, the following array resides within the single block of memory indeed:

char data[4][3] = { {'a','b','c'},{'g','h','i'},{'d','e','f'},{'j','k','l'}};

thus you are able to treat it whatever manner you like, as long as you are trying to access elements that are within the range of this array still. Simple pointer arithmetic like this would do:

int i;
char* ptr = &data[0][0];
for(i = 0; i < 12; i++)
    printf("%c ", *(ptr + i));

yet this would output abcghidefjkl . To make it abcdefghijkl you will probably have to come with something more sophisticated, for example:

int i,j;
char* ptr = &data[0][0];
// a b c d e f:
for(i = 0; i < 2; i++)
    for (j = 0; j < 3; ++j)
        printf("%c ", *(ptr + i*6 + j));
// g h i j k l:
for(i = 0; i < 2; i++)
    for (j = 0; j < 3; ++j)
        printf("%c ", *(ptr + i*6 + j + 3));

note that it is guaranteed by the standard that sizeof(char) will always return 1 , thus it can be omitted. In case of an array of int s, the code would need only 2 changes: ptr would have to be declared as int* and printf should use %d specifier. You still wouldn't have to use sizeof .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM