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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings and pointers

Status
Not open for further replies.

Guest42

Programmer
Nov 9, 2005
28
US
Heya. I have yet another question about pointers and 2D arrays, this time dealing with strings (also, thanks to the guy who helped me last time, it was mighty useful).

When using ints I first allocated memory for the array of pointers, then allocated memory for each pointer, and in doing so clearly had X amount of pointers with X amount of space.

However, with strings, I did this:

char **d;
char *strOne = "Spoo!";
char *strTwo = "Fleemage.";
char *strThree = "Bruce Lee is awesome";


d = (char**)malloc(3*sizeof(strThree));
d[0] = strOne;
d[1] = strTwo;
d[2] = strThree;
strTwo = "Yo";

printf("%s\n", d[1]);
printf("%s\n", strTwo);

This works, but I want to know, is how d is storing it's array of pointers physically. Given that I hadn't allocated space, will it stick d[n] right after the point where d[n-1] ends, given the first thing it's assigned, since it doesn't ultimately know how many pointers it is holding?
 
When you specify a string constant (like "Spoo!"), space is allocated for the string within your program. This space is just large enough to hold the string, and often is allocated in read-only space.

Given your code, if you assign to d[3], your program will happily set the memory in that location. This can cause heap corruption, among other problems. If you're lucky, the program would just crash.

-
 
Right, I had thought so. I took such a long break after programming in C that I had forgotten anyway, that I was going to set the pointers pointing to the actually address of the old strings, rather than taking up new space themselves. Oh well.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top