0

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

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

    }

下面是该函数在中断以解除对指针的引用之前的输出。

输出格式:值@地址

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

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

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

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

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

谢谢,

4

1 回答 1

6

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

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

如果您尝试打印指针地址,printf请使用 this 的格式%p。将您0x%x的 s替换为%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;
}
于 2013-06-18T02:43:03.043 回答