What is the problem with pointers in c?

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

  • Answer:

    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. ...*/

vash47 at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

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().

ufotds

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.

sidyll

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

Suroot

man malloc() You have to allocate your memory to get space!

jDourlens

char **temps; temps[0]=temp2; //crashes The pointer, temps, is uninitialized. Dereferencing it is an undefined operation.

Russell Borogove

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

Carey Gregory

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*.

Sam Hoice

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.