tags:

views:

74

answers:

2

This is something that should be easy to answer, but is more difficult for me to find a particular right answer on Google or in K&R. I could totally be overlooking this, too, and if so please set me straight!

The pertinent code is 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 realize that I can't have char tokens[][] in my tokenize function, but if I put in char **tokens instead, I get a compiler warning. Also, when I try to put a char into my char array with tokens[i][j] = <A CHAR>, I segfault.

Where am I going wrong? (And in how many ways... and how can I fix it?)

Thanks so much!

+5  A: 

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

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

This way, the compiler knows that when you say tokens[2][5] that it needs to do something like:

  1. Find the address of tokens
  2. Move 2 * SIZE bytes past the start
  3. Move 5 more bytes past that address
  4. ???
  5. Profit!

As it stands, without the second dimension specified, if you said tokens[2][5] how would it know where to go?

Mark Rushakoff
Haha, appreciate the final notes: I should have been more explicit and careful there: I do have i, j declared and do have tokens spelled correctly, and the str is an example I effed up: editing my post now. Thanks!
Isaac Hodes
When you say SIZE, are you saying I should tell the function how long the second array is to be (100 in my example) or tell the function what the data-type's size is going to be? (sizeof(char) in my example)
Isaac Hodes
@Isaac: Sorry, `SIZE` as I was using it was meant as in `#define SIZE 100`.
Mark Rushakoff
Ah, so of course, when I declare `tokens` it gives me 100*100 bytes (assuming a char is a byte on the system) in a row. So if I declared char *tokens[100] it would gives me 100 * (sizeof(char*)) bytes in a row. Splendid. Makes total sense! Thanks!
Isaac Hodes
+3  A: 

You're close. Arrays and pointers aren't the same thing, even though it sometimes seems like they are. You can either make your two-dimensional array out 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])
Carl Norum