Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange problem assigning elements of string arrays!!!

Status
Not open for further replies.

GSSV

Programmer
May 29, 2003
2
US
I'm unable to modify any of the individual elements in String arrays, though the array is not declared 'const' .

Eg.
char * Strings[] = { "sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday" };
char **pStrings = Strings;

//Each of the following assignments results in runtime Access Violation error.
//with MS Visual C++ 6.0 as well as the .net version.

Strings[3][5] = 'e'; // runtime exception
*(*(pStrings+3)+5) = 'f'; // runtime exception
pStrings[3][5] = 'g'; // runtime exception

//But each of the above assigments can be made in debug mode, after breaking the execution, say using 'Watch Window'

Can anybody throw some light on this STRANGE PROBLEM please?
 
I have just tried it here:
W2K pro, VC++6.0, but no problems.
Strange it is. I did install service pack 5 for visual studio; that could be one difference between your and mine install.
 
You have an array of pointers... not a 2D array. Those weekdays are string constants, and you have an array of pointers to those constants.
 
> Strings[3][5] = 'e'; // runtime exception
"string" constants are stored in read-only memory. You're not meant to change them at run-time, and so you get an exception if you try.
However, the C standard only states that "string" constants MAY be placed in readonly memory (enforcing at run time what should be a compile time check), so effects vary from one machine to another.

> say using 'Watch Window'
Debuggers are all seeing, all powerful gods looking over your program :)
Memory has to be marked writable when you load the program into memory, but it it marked 'rx' (readonly, executable) when the program is running.
When control returns back to the debugger, then it sets memory back to 'rw' (read/write) so it can change anything you want changed.

> char * Strings[] = { "sunday",
Strictly speaking, this should be
Code:
const char * Strings[] = { "sunday",
then you would start to see some compile time warnings.

 
char Strings[][9]= {"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday"};

tomcruz.net
 
You'll want to make that second dimension at least 10 to allow for the terminating null in "wednesday."
 
Please declare array of poiters to strings as static.The following modification is required for this

static char *Strings[] = { "sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday" };
static char **pStrings = Strings;

Please try and get back.



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top