strtok Unhandled exception;Access violation writing location

后端 未结 2 916
轻奢々
轻奢々 2021-01-26 08:09
#include 
#include 
#include 

char *matrix[10][10];
int main(void) {
    int i;
    char *list[4];
    char *words[20] = {
         


        
相关标签:
2条回答
  • 2021-01-26 08:25
      token = strtok((words[random]),search); 
    
      while(token!=NULL) 
       {
        length=strlen(words[random]);
    
        for( k=0;k<length;k++){
    
          matrix [i][k]=token;
    
            token = strtok(NULL, search); 
    
    
              matrix [i][k]=token;
    
        } 
      }
    

    This is messed and not what you intend. Change it to something straight, e. g.:

        for (k = 0, c = words[random]; token = strtok(c, search); c = NULL, ++k)
            matrix[i][k] = token;
    
    0 讨论(0)
  • 2021-01-26 08:36

    In this statement

    token = strtok((words[random]),search); 
    

    function strtok tries to change a string literal addressed by the array element words[random].

    String literals are immutable in C. Any attempt to change a string literal results in undefined behaviour.

    Instead of the array of pointers to string literals

     char *words[20]={" c a t "," c a r "," b e a r "," s h i p "," m o u s e "," b e a t l e "," c o a t "," n e s t "," i c e "," s u g a r "," b a c o n "," f r o w n "," s m i l e "," d e a d "," f e a t h e r "," g o a t "," h e n "," j e l l y "," k o a l a "," l i p s "};
    

    you should define a two dimensional character array initialized by the string literals. For example

     char words[20][20]={" c a t "," c a r "," b e a r "," s h i p "," m o u s e "," b e a t l e "," c o a t "," n e s t "," i c e "," s u g a r "," b a c o n "," f r o w n "," s m i l e "," d e a d "," f e a t h e r "," g o a t "," h e n "," j e l l y "," k o a l a "," l i p s "};
    
    0 讨论(0)
提交回复
热议问题