Stop Microsoft

Miscellaneous => Programming & Networking => Topic started by: foobar on 7 August 2002, 16:35

Title: C string problems
Post by: foobar on 7 August 2002, 16:35
Hi. Got some q's about C ...

 - How can i add a character to an _existing_ string ?
I've found that:

char *str1 = "joe";
char *str2;

strcpy (str1, str2);

Works, but if you put something into str2 you get signal 11 (segmentation fault).

 - And is it possible to add one single char (not a *char) to a string ?
Title: C string problems
Post by: flap on 7 August 2002, 19:03
That's because str2 is a pointer; you haven't reserved any memory for it to point to.
And strcpy takes the destination as the first param, the source as the second. I think you're thinking of it the other way around.

Try the following:

Code: [Select]

Alternatively you could just set the size of str2 as 9 initially by declaring it as

char str2[9];
Title: C string problems
Post by: foobar on 8 August 2002, 12:19
Indeed, i am still such an idiot at that point.
Anyway thanks, but the last thing you said about simply saing 'char joeblow[9]', doesn't that simply make it an array of characters and not a "real" (real = pointed to by pointer somewhere in your mem) string ? I can only work with real strings ... (it's because of a program i'm working on) or do you know a way to append single char(acters) to a pointer-string ?
Title: C string problems
Post by: voidmain on 8 August 2002, 13:00
His example with the "malloc(9)" is equivelant to "str2[9]".  They both allocate a specific amount of space to hold your string.  If you do not allocate space to hold your string then you will randomly overwrite memory and your program will crash (C lets you do that, it assumes you know what you are doing).  And yes, a string in C is nothing more than an array of characters as C does not have a "string" type. In C a string should be null (\0) terminated.  If it is not, the string functions will not work properly.  You might want to take a look at this as it may help:

http://www.macdonald.egate.net/CompSci/hstrings.html (http://www.macdonald.egate.net/CompSci/hstrings.html)
and
http://www.sysprog.net/cstring.html (http://www.sysprog.net/cstring.html)