-2

I have a c code that tokenize the content of my file. I want to copy/assign each token to a temp variable to put it into a list. My temp was declared as char *temp[MAX]. Here is my code but there is something wrong in strcpy(temp[k], token). When i run my code, it force close my program. However, when I remove the strcpy line/statement, it runs correctly and does not force close. But my goal to copy the tokens to temp will not be done. Can somebody know why this is happening? Thank you.

Declaration of temp is global: char *temp[MAX];

void tokenize(FILE *input){

char *token;
int k=0;

char word[1000];
while(!feof(input)){
    fgets(word,1000,input);
    token = strtok(word, " \t\n");
        while(token!=NULL){             
            printf("%s\n",token);
            strcpy(temp[k], token);
            k++;
            token= strtok(NULL, " \t\n");
        }
}
printf("%s", temp[0]);
}
BoJack Horseman
  • 159
  • 5
  • 15
  • [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – M.M Nov 29 '15 at 10:52
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Nov 29 '15 at 10:54
  • you need allocate space for `temp[k]` before copy from `token`. – BLUEPIXY Nov 29 '15 at 10:57
  • how can i allocate space for temp[k]? anyway, the program runs correctly if i remove the strcpy line however, my goal to copy the tokens to temp will be a failure. – BoJack Horseman Nov 29 '15 at 11:04
  • E.g `temp[k] = malloc(strlen(token)+1); strcpy(temp[k], token);` – BLUEPIXY Nov 29 '15 at 11:05
  • @BLUEPIXY, there's an error saying invalid conversion from 'void*' to 'char*' – BoJack Horseman Nov 29 '15 at 11:08
  • you used C++ as C. So `temp[k] = (char*)malloc(strlen(token)+1);` – BLUEPIXY Nov 29 '15 at 11:09

1 Answers1

0

You need to allocate space for temp before you can use it. Did you do that?

temp[k] = (char *) malloc(strlen(token)+1);

Add this line to your code before you assign value to temp[k].

Srujan Barai
  • 2,295
  • 4
  • 29
  • 52