Gustavo Puma
Gustavo Puma

Reputation: 1055

Problem with C pointers in 2d char arrays

Why does this work:

    //split returns (char**)
    char *temp2;
    temp2=split(array[i],'=')[1];

and this doesn't:

char **temps;
temps[0]=temp2; //crashes

or this:

temps[0]=split(array[i],'=')[1]; //crashes

Upvotes: 1

Views: 633

Answers (8)

user1115652
user1115652

Reputation:

Split returns a pointer to a pointer to a char. So, what is returned from split(array[i],'=')[1] is a pointer to char which is what you declared on the stack and thus reserved space for it. That is why it works.

The other two don't work because the space pointed to is not allocated. You should use malloc().

Upvotes: 2

Jonathan Adelson
Jonathan Adelson

Reputation: 3321

Think of it this way:

char *temp2 = "foo";

char **temps;

temps[0] = temp2; // won't work
temps = &temp2; // ok

temp2 points at a C string. You can point temps at the address of temp2, (&temp2) but you can't dereference temps (that is, temps[0]) unless you first make it point at something valid. From your question it sounds like you want to malloc() an array of char* first.

In the second and third cases, you are dereferencing temps[0] without first making it refer to some valid memory location. As has been pointed out, temps is pointing at a garbage location.

Your first case works because you're dereferencing split(), so it's giving you a char*.

Upvotes: 0

Carey Gregory
Carey Gregory

Reputation: 6846

Because temps isn't initialized. It's a random value pointing to a random memory location.

Upvotes: 0

Russell Borogove
Russell Borogove

Reputation: 19037

char **temps;
temps[0]=temp2; //crashes

The pointer, temps, is uninitialized. Dereferencing it is an undefined operation.

Upvotes: 0

GrandMarquis
GrandMarquis

Reputation: 1913

man malloc()

You have to allocate your memory to get space!

Upvotes: 0

Suroot
Suroot

Reputation: 4423

char **temps was never allocated any space. You're dereferencing bad memory with temps[0].

Upvotes: 0

sidyll
sidyll

Reputation: 59287

If you simply declare a pointer variable:

char **temps;

It's not really pointing to somewhere. Well, it actually is, but that's probably garbage (anywhere in memory). You have to initialize it before using it. Try allocating space for it.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477060

temps is just a pointer to a char*, but it has no initalized, sensible value! temps[0] is equivalent to *(temps + 0), but you cannot dereference a garbage value -- you first have to make temps points somewhere useful, e.g. by allocating memory for it.

If you want to store some char*s with automatic storage, then declare an array of char pointers instead:

char * temps[20];
temps[0] = /*... etc. ...*/

Upvotes: 2

Related Questions