Declaring an array of character pointers (arg transition)

This is something that should be easy to answer, but it’s harder for me to find the specific correct answer on Google or in K & R. I could completely forget about it, and if so, please configure me directly!

The corresponding code is given below:

int main(){ char tokens[100][100]; char *str = "This is my string"; tokenize(str, tokens); for(int i = 0; i < 100; i++){ printf("%s is a token\n", tokens[i]); } } void tokenize(char *str, char tokens[][]){ int i,j; //and other such declarations //do stuff with string and tokens, putting //chars into the token array like so: tokens[i][j] = <A CHAR> } 

So, I understand that I cannot have char tokens[][] in my tokenize function, but if I put char **tokens in char **tokens instead, I get a compiler warning. Also, when I try to put char in my char array with tokens[i][j] = <A CHAR> , I am segfault.

Where am I mistaken? (And how ... and how can I fix it?)

Many thanks!

+4
source share
2 answers

You will need to specify the size of the second dimension of the array:

 #define SIZE 100 void tokenize(char *str, char tokens[][SIZE]); 

Thus, the compiler knows that when you tell tokens[2][5] that he needs to do something like:

  • Find the tokens address
  • Move 2 * SIZE bytes to the beginning
  • Move another 5 bytes to this address
  • ???
  • Profit!

Anyway, without specifying the second dimension, if you told tokens[2][5] how would he know where to go?

+5
source

You're close Arrays and pointers are not the same thing, although sometimes it seems that they are. You can either make your two-dimensional array outside of pointers:

  char **tokens = malloc(100 * sizeof(char *)); for (i = 0; i < 100; i++) tokens[i] = malloc(100); 

And then use:

 void tokenize(char *str, char **tokens) 

or you can specify the size of the array in your tokenize() function:

 void tokenize(char *str, char tokens[][100]) 
+3
source

Source: https://habr.com/ru/post/1308826/


All Articles