Author Topic: C string problems  (Read 1147 times)

foobar

  • Member
  • **
  • Posts: 308
  • Kudos: 0
    • http://www.fuckmicrosoft.com
C string problems
« 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 ?
Linux user #283039

Gosh, I love Linux Quake.


flap

  • Member
  • **
  • Posts: 1,268
  • Kudos: 137
C string problems
« Reply #1 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];
"While envisaging the destruction of imperialism, it is necessary to identify its head, which is none other than the United States of America." - Ernesto Che Guevara

http://counterpunch.org
http://globalresearch.ca


foobar

  • Member
  • **
  • Posts: 308
  • Kudos: 0
    • http://www.fuckmicrosoft.com
C string problems
« Reply #2 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 ?
Linux user #283039

Gosh, I love Linux Quake.


voidmain

  • VIP
  • Member
  • ***
  • Posts: 5,605
  • Kudos: 184
    • http://voidmain.is-a-geek.net/
C string problems
« Reply #3 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
and
http://www.sysprog.net/cstring.html
Someone please remove this account. Thanks...