R
Rick
Hi,
This is probably simple byt when you never did pointers and being used to
luxery strings like in Delphi or Visual Basic, C can get though. What I'm
trying to do is to add chars to a string. I looked in the string.h file but
I didn't find that kind of function (that string library is more than 7
years old) so I decided to write that function on myself. It seems to work
although when I'm trying to do printf's between those actions I get strange
messages. Anyway, now I'm trying to add chars to 2 strings. The first string
is ok but the second one seems to get overwrited. Here's my code :
/* the function to add 1 char to a string */
char *strAddChar(char *s1, char c){
char *s;
s = s1;
s = s + strlen(s1); // the position to write
*s = c; // this should be on the place where the null char
first
// was.
s++;
*s = 0; // add a new null string
return(s1);
} // strAddChar
/* this is how I use the function */
main(){
char *res1 = ""; // empty string 1
char *res2 = ""; // empty string 2
strAddChar( res1, 'a' );
strAddChar( res1, 'b' );
strAddChar( res1, 'c' );
strAddChar( res2, '1' );
strAddChar( res2, '2' );
strAddChar( res2, '3' );
printf( "%s\n",res1 ); // test
printf( "%s\n",res2 );
Ok, the output should be res1="abc" and res2="123" but this is my result :
res1="abc" res2="bc123"
How does "bc" come in res2?? How to fix the function?
Greetings,
Rick
This is probably simple byt when you never did pointers and being used to
luxery strings like in Delphi or Visual Basic, C can get though. What I'm
trying to do is to add chars to a string. I looked in the string.h file but
I didn't find that kind of function (that string library is more than 7
years old) so I decided to write that function on myself. It seems to work
although when I'm trying to do printf's between those actions I get strange
messages. Anyway, now I'm trying to add chars to 2 strings. The first string
is ok but the second one seems to get overwrited. Here's my code :
/* the function to add 1 char to a string */
char *strAddChar(char *s1, char c){
char *s;
s = s1;
s = s + strlen(s1); // the position to write
*s = c; // this should be on the place where the null char
first
// was.
s++;
*s = 0; // add a new null string
return(s1);
} // strAddChar
/* this is how I use the function */
main(){
char *res1 = ""; // empty string 1
char *res2 = ""; // empty string 2
strAddChar( res1, 'a' );
strAddChar( res1, 'b' );
strAddChar( res1, 'c' );
strAddChar( res2, '1' );
strAddChar( res2, '2' );
strAddChar( res2, '3' );
printf( "%s\n",res1 ); // test
printf( "%s\n",res2 );
Ok, the output should be res1="abc" and res2="123" but this is my result :
res1="abc" res2="bc123"
How does "bc" come in res2?? How to fix the function?
Greetings,
Rick