-3
char **three = (char**)malloc(sizeof(char*));

char**, the char pointer type is used. and char** means I'm dereferencing char pointer. and as for the sizeof(char*) I'm using the size of char pointer which is 8 byte.

Am I misunderstanding this?

mrflash818
  • 930
  • 13
  • 24

2 Answers2

3

So the code:

char **three = ( char** )malloc( sizeof( char* ) );

Allocates an array of pointers-to-char, but with only a single element. The variable three is a pointer-to, a pointer-to a char. Much the same as:

char *three[1];

Normally (as @paxdiablo points out), it would be more usual to allocate a number of pointers:

int line_count = 66;
char **three = ( char** )malloc( line_count * sizeof( char* ) );

Once allocated, this can be used with array notation:

three[0] = "The Owl and the Pussy-cat went to sea";
three[1] = "In a beautiful pea-green boat,";
three[2] = "They took some honey, and plenty of money,";
three[3] = "Wrapped up in a five-pound note."

There's nothing particularly special about a char**, every C/C++ program gets one as its argv.

As a programmer, you don't really know that your pointer is 8 bytes, you know the pointer will be some size. This is where the sizeof( char* ) comes in. During compilation the compiler swaps this with the real value. That way when the architecture is 16, 32 or 64 bit (or maybe 128 bit in the future), the code still compiles fine.

Kingsley
  • 14,398
  • 5
  • 31
  • 53
2

Let's see if we can break this down:

char **three = (char**)malloc(sizeof(char*));
[     1    ][5][  4   ][ 3  ] [    2      ]
  1. Create a variable three of type char **, a pointer to a char * (often a "string" in C).
  2. Use the size of a char* to pass to malloc.
  3. Use malloc to allocate that many bytes.
  4. Cast the return value from malloc, a void*, to char**.
  5. Assign that value to three.

So in terms of where I think your misunderstanding lies:

  • Do not cast the return value of malloc or realloc in C. C is perfectly capable of implicitly casting void* to other pointer types and doing it explicitly can hide certain subtle errors.
  • There is no dereferencing going on here. The (unwise) cast is exactly that, telling the compiler you want to treat an expression of one type as if it was another type.
  • You've actually allocated an array of char* variables and that array size is one. So, short of calling realloc on it at some point, its use is limited (unless you need it to survive the current scope, you're probably just better using a local variable rather than an allocated one-element array).
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953