开发者

Arrays in C not working

Well, I declared a global array of chars like this char * strarr[];

in a method I am tokenising a line and try to put everything into that arra开发者_如何转开发y like this

*line =  strtok(s, " ");

while (line != NULL) {
  *line = strtok(NULL, " ");
}

seems like this is not working.. How can I fix it?

Thanks


Any number of things could be going wrong with the code you haven't shown us, such as undefined behaviour by strtoking a string constatnt, or getting your parameters wrong when calling the function.

But the most likely problem from the code we can see is the use of *line instead of line, assuming that line is of type char *.

Use the following code as a baseline:

#include <stdio.h>
#include <string.h>

int main (void) {
    char str[] = "My name is paxdiablo";

    // Start tokenising words.

    char *line =  strtok (str, " ");
    while (line != NULL) {
        // Print current token and get next word.

        printf ("[%s]\n", line);
        line = strtok(NULL, " ");
    }

    return 0;
}

This outputs:

[My]
[name]
[is]
[paxdiablo]

and should be easily modifiable into something you can use.

Be aware that, if you're trying to save the character pointers returned from strtok (which would make sense for using *line), they are transitory and will not be what you expect after you're done. That's because modifications are made in-place within the source string. You can do it with something like:

#include <stdio.h>
#include <string.h>

int main (void) {
    char *word[4];         // The array of words.
    size_t i;              // General counter.
    size_t nextword = 0;   // For preventing array overflow.

    char str[] = "My name is paxdiablo";

    // Start tokenising.

    char *line =  strtok (str, " ");
    while (line != NULL) {
        // If array not full, duplicate string to array and advance index.

        if (nextword < sizeof(word) / sizeof(*word))
            word[nextword++] = strdup (line);

        // Get next word.

        line = strtok(NULL, " ");
    }

    // Print out all stored words.

    for (i = 0; i < nextword; i++)
        printf ("[%s]\n", word[i]);

    return 0;
}

Note the specific size of the word array in that code above. The use of char * strarr[] in your code, along with the message tentative array definition assumed to have one element is almost certainly where the problem lies.

If your implementation doesn't come with a strdup, you can get a reasonably-priced one here :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜