0

Here's what I got:

char ***tokens;
*tokens=(char**)malloc((5)*sizeof(char*));
*tokens[4]=(char*)malloc((4)*sizeof(char));

And I got "Program received signal SIGSEGV, Segmentation fault." At the third line.

The thing is, this is okay:

*tokens[0]=(char*)malloc((4)*sizeof(char));

And this is okay too:

*tokens[1]=(char*)malloc((4)*sizeof(char));

But this gives me segmentation fault:

*tokens[2]=(char*)malloc((4)*sizeof(char));

Or any number bigger than 2, why is that when the array should have a length of 5?

The idea is that I have a pointer that points to an array, each set of the array points to a string, so I can do something like this:

*tokens[0]="string";

And

(*tokens[0])[m]='s';
6
  • 3
    What's tokens variable definition? Commented Apr 16, 2014 at 9:30
  • 3
    There's no way that code compiled. Also, show the declaration of tokens, and don't cast the return value of malloc() in C. Commented Apr 16, 2014 at 9:31
  • And show some relevant code. Commented Apr 16, 2014 at 9:37
  • how can you directly assain to *tokens? Commented Apr 16, 2014 at 9:38
  • tokens : uninitialize. and should be (*tokens)[4]=(char*)malloc((4)*sizeof(char)); Commented Apr 16, 2014 at 9:40

1 Answer 1

2

What's exactly that you want to do? It seems that char **tokens would be a better solution to your problem.

In this moment, when you are doing

 *tokens=(char**)malloc((5)*sizeof(char*));

you are writing in the unallocated memory area pointed by the uninitialized variable tokens. Where it crashes afterwards then it is more or less random.

The idea is that I have a pointer that points to an array, each set of the array points to a string, so I can do something like this:

*tokens[0]="string";

To which memory area do you think that variable will be pointing too?
I suggest you read Pointer to const string in C, which explains why (*tokens[0])[m]='s'; would be illegal. You should also learn about commands like strcpy and the like.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.