Code Monkey
Code Monkey

Reputation: 17

Pointer Pointing to Pointer

Lets say I have a variable:

char** code;

I then do:

*code[0] = "Lucas"

Is it valid to say that, **code holds an array of pointers (*code is the array which I am making strings) and that *code[0] will equal "Lucas" and that *code[0][2] will equal 'c'?

Sorry if it seems elementary, I am getting very confused with double pointers! Thanks in advance!

-Lucas Giancola

Upvotes: 0

Views: 48

Answers (2)

R Sahu
R Sahu

Reputation: 206567

If you just have

char** code;
*code[0] = "Lucas";

you'll run into undefined behavior since you did not allocate any memory for code.

You'll need to use:

char** code = malloc(SOME_SIZE*sizeof(*code));

Even after that, using:

*code[0] = "Lucas";

is not good. There are couple of problems with that.

  1. code[0] is a pointer. *code[0] is that pointer dereferenced. If you already have some string in code[0], then, *code[0] will be first character of that string. The assignment is, therefore, wrong.

  2. Also, "Lucas" is going to be in a read-only parts of the compiled code. You will need to make a copy of "Lucas" using strdup before you assign it to a variable that is of type char *.

You need something like:

 code[0] = strdup("Lucas");

Now you can use code[0] to access the whole string. You can use *code[0] to access the first character of that string. You can also use code[0][0] to access the first character of that string.

Upvotes: 2

pm100
pm100

Reputation: 50110

Is it valid to say that, **code holds an array of pointers

No it is not. You have allocated space for a single pointer. You have told the compiler that that pointer will point at another pointer (that you have not created yet) that points to a character (that you have not created yet either)

*code[0] = "Lucas"

Is not valid code and doesnt compile

prog.cpp:6:8: error: invalid conversion from 'const char*' to 'char' [-fpermissive]
  *f[0] = "Lucas";

Upvotes: 3

Related Questions