Reputation: 71
I keep trying different configurations of this code with "*"s, but can't get it to output the address of board. What am I missing?
We need to dynamically allocate a 2-d array for a map. I can't change the createMapBoard function line for the project, and the ** is throwing me off.
#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;
}
Upvotes: 1
Views: 82
Reputation: 23236
Change this:
printf("Pointer: %s\n", pointer); // "%s" is for printing string
^
to this:
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.
^
There is a cheat sheet here for printf
format specifiers, including one for pointer addresses.
By the way, this particular format specifier is also useful for printing the address of other variable types when using it in conjunction with the &
(address of) operator:
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.
Upvotes: 3
Reputation: 225344
You have two problems here. First, the %s
format specifier is used to print a string. If you want to print the value of a pointer, use %p
and cast the operand to void *
:
printf("Pointer: %p\n", (void *)pointer);
Second, what you're assigning to pointer
is actually a pointer to the first string in the board, not the whole board. For that you want:
char **pointer = createMapBoard();
Then you can treat pointer
as an array to iterate through the strings.
Upvotes: 3