C 通过指针访问二维字符数组

ila*_*ila 0 c pointers multidimensional-array

我正在尝试访问一个二维字符数组。我有一个指向正确地址的指针,但以某种方式引用不起作用。

    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));

    }
Run Code Online (Sandbox Code Playgroud)

以下是此功能在中断以取消对指针的引用之前的输出。

输出格式:值@地址

0x100@0x5fbff408 == 0x5fbff408
0x101@0x5fbff410 == 0x5fbff410
0x102@0x5fbff418 == 0x5fbff418
0x103@0x5fbff420 == 0x5fbff420
0x104@0x5fbff428 == 0x5fbff428
Run Code Online (Sandbox Code Playgroud)

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

但是当指针是尊重时,它就会在那里中断。即使使用 [] 操作符也是如此。

*(a_ptr + i); //Breaks
a_ptr[i]; //Breaks as well
Run Code Online (Sandbox Code Playgroud)

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

谢谢,

Nob*_*lis 6

char **a_ptr = &ary;——这毫无意义。char** a_ptr是一个指向指针的指针。你需要的是一个指向数组的指针。将执行以下操作:

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

如果您尝试打印指针地址,请printf使用 this 的格式%p。将您的0x%xs替换为%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;
}
Run Code Online (Sandbox Code Playgroud)

现在我的输出是:

$ ./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
Run Code Online (Sandbox Code Playgroud)

这是你希望得到的吗?

一些仅依赖指针而不依赖数组的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)