0

1.
I am using strtok() and am storing the return value into a char array.

eg. char word[];
word = strtok(file[][], " ");

Do I need to initialize 'word' to a constant size before using it? The thing is I don't know how big the string from strtok is going to be and I will constantly be using 'word' to store different size strings I pull from strtok each time I call it.

Also when I am testing to make sure word is not NULL (since when nothing is left on the line I am reading from, strtok returns NULL) which one of these work?

eg. if(word != NULL) or if(word[0] != NULL)

2.
What is the function for finding the size of of a two dimensional array's first dimension?

eg. char array[ the size of this one ] []

Thanks

2
Contributors
1
Reply
3
Views
12 Years
Discussion Span
Last Post by Narue
0

>Do I need to initialize 'word' to a constant size before using it?
Yes, otherwise it's an incomplete type that you can't use.

>The thing is I don't know how big the string from strtok is going to be
>and I will constantly be using 'word' to store different size strings I pull from strtok each time I call it.
Well then, it's convenient that you can't assign to arrays like you're attempting, isn't it? :) strtok returns a pointer to char, which is very different from an array of char. You can save the pointer returned by strtok, test its length with strlen, then act accordingly. The choice at that point is to make the array "big enough for anything" and flag errors when something is too big, or use dynamic memory (not forgetting to free it when you're done):

char *p;
char word[1024];

p = strtok ( line, " " );
if ( p == NULL )
  return;
if ( strlen ( p ) >= sizeof word )
  panic();
char *p;
char *word;

p = strtok ( line, " " );
if ( p == NULL )
  return;
word = malloc ( strlen ( p ) + 1 );
if ( word == NULL )
  return;
strcpy ( word, p );

Of course, this begs the question, why do you need a copy in the first place? Can't you just use the pointer that strtok gives you? That would be much easier.

>which one of these work?
Neither. An array cannot be NULL because it's not a pointer.

>What is the function for finding the size of of a two dimensional array's first dimension?
You can use the sizeof operator for this, but it's easier to just remember the size, since it's known at compile-time.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.