Why strtok() don't work with char *?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ali Uruji
    New Member
    • Jan 2011
    • 1

    Why strtok() don't work with char *?

    Hi, I'm trying to write a simple program in VC++ 2010 to tokenize a sentence.
    Yet, the code I wrote do not cause any compilation errors( regardless of warnings about strtok ) but when its executed it stops working. This is the code:

    Code:
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    int main(){
    	char *line = "int a = 10, b; ";
    	char *token;
    
    	token = strtok( line, " " ); 
    
    	cout << token;
    
            return 0;
    }
    This program seems to have a problem with strtok() because of these:



    And one another thing: why when I change
    Code:
     char *line
    to
    Code:
     char line[]
    ... it works correctly?
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    in line 7
    Code:
        char *line = "int a = 10, b; ";
    the text "int a = 10, b; " is a string constant and the gcc compiler displays the warning (if warnings are enbled)
    Code:
     warning: deprecated conversion from string constant to 'char*'
    therefore the variable line points to a string constant
    you can print its contents OK so
    Code:
       cout << line << endl;
    because the statement does not attempt to modify the string

    however, the first parameter to strtok() cannot be a pointer to a constant as the contents of the string are modified and broken into smaller strings (tokens) by strtok(). see

    it is when strtok() trys to modify the constant string "int a = 10, b; " the program crashes with a memory error.

    changing line 7 to
    Code:
        char line[] = "int a = 10, b; ";
    works because the string not a constant it is an array which can be modified

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      works because the string not a constant it is an array which can be modified
      Strictly and pedantically speaking the string is still a constant but it is copied into a non-constant array of char line and this is what is modified.

      Comment

      Working...