954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

problem in strtok

Hi

I am writing a code in VC++

char* style = "color:#4D4DFF;font-size:9pt;font-family:Arial;";
char* semicolonsplit = "";
semicolonsplit = strtok (style,";");
But in the last line I am getting an error

" Access violation writing location 0x0041606d."

Am I missing something.

Regards
Karan

karang
Light Poster
46 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

use char arrays instead of char pointers.

iDeveloper
Light Poster
49 posts since Jul 2008
Reputation Points: 31
Solved Threads: 7
 

>Am I missing something.
Yes. iDeveloper gave you the fix, but the reason for it is that you're initializing pointers to string literals. The problem isn't the pointers per se, it's the initialization of a pointer to a string literal. A string literal in C++ is defined as an array of const char, and strtok modifies the first argument by writing null characters at each delimiter. The access violation comes from strtok trying to write to read-only memory.

By changing style from a pointer to an array, the initialization changes as well. Instead of assigning the address of the string literal to a pointer, you're copying the contents of the string literal to a non-const array that you own and can modify.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You