C通过指针访问2D字符数组

时间:2013-06-18 02:27:06

标签: c pointers multidimensional-array

我正在尝试访问字符的二维数组。我在正确的地址上有一个指针,但不知何故,dreferencing无效。

    char ary[5][8];
char temp[8];
int i;

char **a_ptr = &ary;

    for(i=0; i<5; i++){
        sprintf(temp, "0x10%d" , i);
        strcpy(ary[i] , temp);
        printf("~~~%s@0x%x == 0x%x" , ary[i] , &ary[i] , (a_ptr + i));

    }

    for(i=0; i<5; i++){//This wont work. 
        printf("~~~%s@0x%x" , *(a_ptr + i) ,  (a_ptr + i));

    }

下面是这个fucniton在断开以解除指针之前的输出。

输出格式:值@地址

0x100@0x5fbff408 == 0x5fbff408
0x101@0x5fbff410 == 0x5fbff410
0x102@0x5fbff418 == 0x5fbff418
0x103@0x5fbff420 == 0x5fbff420
0x104@0x5fbff428 == 0x5fbff428

正如我们在上面的输出中看到的那样,数组值被正确填充并且a_ptr指向正确的地址(&amp; ary [i] ==(a_ptr + i))。

但是当指针是deference时,它会在那里中断。即使使用[]运算符也是如此。

*(a_ptr + i); //Breaks
a_ptr[i]; //Breaks as well

但是,(a_ptr + i)指向正确的地址。

谢谢,

1 个答案:

答案 0 :(得分:4)

char **a_ptr = &ary; - 这没有任何意义。 char** a_ptr是指向指针的指针。你需要的是一个指向数组的指针。以下是:

char (*a_ptr)[8] = ary; // also don't take the address of the array

如果您尝试打印指针地址,printf的格式为%p。将0x%x替换为%p

我编写了如下代码,我的编译器不再发出警告:

#include <stdio.h>
#include <string.h>

int main()
{
    char ary[5][8];
    char temp[8];
    int i;

    char (*a_ptr)[8] = ary;

    for(i=0; i<5; i++)
    {
        sprintf(temp, "0x10%d" , i);
        strcpy(ary[i] , temp);
        printf("~~~%s@%p == %p" , ary[i] , &ary[i] , (a_ptr + i));

    }

    for(i=0; i<5; i++)
    {
        printf("~~~%s@%p" , *(a_ptr + i) ,  (a_ptr + i));
    }

    return 0;
}

现在我的输出是:

$ ./a.out 
~~~0x100@0xbfc77a74 == 0xbfc77a74~~~0x101@0xbfc77a7c == 0xbfc77a7c~~~0x102@0xbfc77a84 == 0xbfc77a84~~~0x103@0xbfc77a8c == 0xbfc77a8c~~~0x104@0xbfc77a94 == 0xbfc77a94~~~0x100@0xbfc77a74~~~0x101@0xbfc77a7c~~~0x102@0xbfc77a84~~~0x103@0xbfc77a8c~~~0x104@0xbfc77a94

这是你希望得到的吗?

某些代码仅依赖于指针而没有数组:

#include <stdio.h>
#include <string.h> /* for strcpy */
#include <stdlib.h> /* for free and malloc */

int main()
{

    char** two_d = malloc(sizeof(char*) * 5); /* allocate memory for 5 pointers to pointers */

    int i;
    for(i = 0; i < 5; i++) /* for each of the five elements */
    {
        two_d[i] = malloc(2); /* allocate memory to each member of two_d for a 2 char string */

        strcpy(two_d[i], "a"); /* store data in that particular element */

        printf("%s has address of %p\n", two_d[i], &two_d[i]); /* print the contents and the address */

        free(two_d[i]); /* free the memory pointer to by each pointer */
    }

    free(two_d); /* free the memory for the pointer to pointers */

    return 0;
}