需要打印地址但获取内容

时间:2019-01-21 20:19:58

标签: c pointers

我一直尝试使用“ *”来配置此代码的不同配置,但无法获取它来输出电路板的地址。我想念什么?

我们需要为地图动态分配2维数组。我无法更改该项目的createMapBoard函数行,而**会让我失望。

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

char **createMapBoard(void)
{
    int i;
    char **board;

    board = malloc(8 * sizeof(char *));
    for(i = 0; i < 8; i++)
        board[i] = malloc(8 * sizeof(char));

    strcpy(board[0],"FF      ");
    strcpy(board[1]," F      ");
    strcpy(board[2]," FF     ");
    strcpy(board[3],"  F     ");
    strcpy(board[4],"  K     ");
    strcpy(board[5],"C  B    ");
    strcpy(board[6]," CC D   ");
    strcpy(board[7],"  C  DD ");

    return board;
}

int main()
{

char *pointer = *createMapBoard();
printf("Pointer: %s\n", pointer);
return 0;
}

2 个答案:

答案 0 :(得分:3)

更改此:

printf("Pointer: %s\n", pointer); // "%s" is for printing string
                  ^

对此:

printf("Pointer: %p\n", (void *)pointer); // "%p" is for printing pointer addresses
                                          // Note: cast to (void *) is optional for use with 
                                          // character types (but idiomatic),  and necessary 
                                          // for other types when using "%p" format specifier.
                  ^

printf格式说明符有一个 cheat sheet here ,其中一个包含指针地址

顺便说一句,当与& 的地址)一起使用时,此特殊的格式说明符对于打印其他变量类型的地址也很有用:

int int_var;

printf("This is the address of int_var: %p\n", (void *)&int_var);//note, (void *) cast is 
                                                                 //necessary here as its applied 
                                                                 //to non-character type.

答案 1 :(得分:3)

您在这里有两个问题。首先,%s格式说明符用于打印字符串。如果要打印指针的值,请使用%p并将操作数强制转换为void *

printf("Pointer: %p\n", (void *)pointer);

第二,您要分配给pointer的实际上是指向棋盘中第一个字符串的指针,而不是整个棋盘的指针。为此,您想要:

char **pointer = createMapBoard();

然后,您可以将pointer当作一个数组来遍历字符串。