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';

1 Answers1

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.

Community
  • 1
  • 1
Antonio
  • 19,451
  • 13
  • 99
  • 197