473,785 Members | 2,400 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding chars to a string

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(cha r *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
Nov 13 '05 #1
23 31091
In article <3f************ ***********@new s.xs4all.nl>, Rick wrote:
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.

Did you investigate strcat() and strncat()?
--
Andreas Kähäri
Nov 13 '05 #2
To add, I think result2 get's overwritten by result1 somehow. When those 2
got initialized they get a memory adress automatically and it seems that
when I'm adding chars to result1, result2 won't move further. Result1
probably only get 1 byte of memory so when adding the second char it's "out
of bounds" and contineus on result2.

If this is true, that would be quiete dangerous because I could overwrite a
big part of the program. Normally you can use arrays and malloc them but in
my case, I really don't know how big the result becomes. While building the
result string, I need at least 1 sub string for other stuff, that string has
the same problem, I can't calculate how big it becomes, it has to grow
dynamically. How to handle this?

Greetings,
Rick
Nov 13 '05 #3
You answered faster than the light! I just tried it but the same problem
(see that other post where I explained the problem a little bit more). Or
maybe I am using the code wrong, this is what I did with strncat:

char *res1 = "";
char *res2 = "";
strncat( res1, "a",1 );
strncat( res1, "b",1 );
strncat( res1, "c",1 );
strncat( res2, "1",1 );
strncat( res2, "2",1 );
strncat( res2, "3",1 );
printf( "result1 %s\n",res1 );
printf( "result2 %s\n",res2 );

result : res1 = "abc" res2="bc123". When using strcat the same.

Greetings,
Rick


Nov 13 '05 #4
"Rick" <as******@hotma il.com> wrote in
news:3f******** *************** @news.xs4all.nl :
You answered faster than the light! I just tried it but the same problem
(see that other post where I explained the problem a little bit more).
Or maybe I am using the code wrong, this is what I did with strncat:

char *res1 = "";
char *res2 = "";
HEY! You have to allocate writable memory for these pointers.
strncat( res1, "a",1 );


NO! You cannot write to res1 or res2. Look up malloc() and use it, then
come back. The res1 pointer is pointing to non-writable memory at this
point. Some implemtations will allow this, others will crash. What if the
compiler put the null string that res1 points to in FLASH or PROM? How
could you write to that?

--
- Mark ->
--
Nov 13 '05 #5
In article <3f************ ***********@new s.xs4all.nl>, Rick wrote:
You answered faster than the light! I just tried it but the same problem
(see that other post where I explained the problem a little bit more). Or
maybe I am using the code wrong, this is what I did with strncat:

char *res1 = "";
char *res2 = "";
strncat( res1, "a",1 );


You're not allowed to modify the contents of the string pointed
to by res1 or res2, the way you defined them. Both pointers
must point to a sufficiently large portion of allocated memory.

See here:

#include <stdio.h>
#include <string.h>

int
main(void)
{
char res1[10] = ""; /* Must be long enough */
char res2[10] = ""; /* Must be long enough */

/* strncat(res1, "abc", 3), but more verbose: */
strncat(res1, "a", 1);
strncat(res1, "b", 1);
strncat(res1, "c", 1);

/* strncat(res2, "123", 3), but more verbose: */
strncat(res2, "1", 1);
strncat(res2, "2", 1);
strncat(res2, "3", 1);

printf("res1 = '%s'\nres2 = '%s'\n", res1, res2);

return 0;
}

Result:
res1 = 'abc'
res2 = '123'

--
Andreas Kähäri
Nov 13 '05 #6
"Rick" <as******@hotma il.com> writes:
Hi,
char *strAddChar(cha r *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 ^^^ ^^^^ res1 points to an (possibly)
non-writable array of 2 chars,
char *res2 = ""; // empty string 2
the same here...
strAddChar( res1, 'a' );


and here you invoke undefinde behaviour by writting to res1 ( and
writing past the end.

C-strings do not grow automagically, you would have to do this by
mallocing enough memory somewhere.

Björn

--
Bjoern Pedersen Lichtenbergstr. 1
Technische Universitaet Muenchen D-85747 Garching
ZWE Instrumentierun g FRM-II
Tel. + 49 89 289-14707 Fax -14666
Nov 13 '05 #7
Rick wrote:
If this is true, that would be quiete dangerous because I could overwrite a
big part of the program. Normally you can use arrays and malloc them but in
my case, I really don't know how big the result becomes. While building the
result string, I need at least 1 sub string for other stuff, that string has
the same problem, I can't calculate how big it becomes, it has to grow
dynamically. How to handle this?


use realloc(), which resizes malloc()'d buffers. e.g.,
char *s;

s = malloc(4);
if (s == NULL) {
/* ... */
}
strcpy(s, "foo");
s = realloc(s, 4+3);
if (s == NULL) {
free(s);
/* ... */
}
strcat(s, "bar");
if your system has them, consider using strlcpy()/strlcat().
http://www.openbsd.org/papers/strlcpy-paper.ps

--
Segui il tuo corso, e lascia dir le genti.

Lars

Nov 13 '05 #8
Andreas Kahari <ak*******@free shell.org> wrote in
news:sl******** **************@ mx.freeshell.or g:

Andreas, let's be sure Rick sees the important change...
int
main(void)
{
char res1[10] = ""; /* Must be long enough */
char res2[10] = ""; /* Must be long enough */

^^^^

Rick, note that these are arrays of chars, not pointers to chars. That's
the key.

--
- Mark ->
--
Nov 13 '05 #9
Everybody thanks for helping I understand the problem. It's now working with
fixed sized arrays.

Greetings,
Rick
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3611
by: David | last post by:
I have an array that contains numbers in string elements , i want to convert this to integers, i have made a for loop that uses the number of elements in the array and then adds 0, thereby converting it to an integer. //$chars is the array of strings for ($i=0; $i<$numpoints; $i++) { $array = array($chars + 0); } I dont know though how to add all these elements to the 1 array, it
4
7415
by: Neil W. | last post by:
I'm coming back to Perl after a long absence. I am trying to add up the ascii values of the characters in a string. Can anyone refresh my memory? Thanks.
4
8826
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where a * occurs in the string). This split function should allocate a 2D array of chars and put the split results in different rows. The listing below shows how I started to work on this. To keep the program simple and help focus the program the...
9
6280
by: Durgesh Sharma | last post by:
Hi All, Pleas help me .I am a starter as far as C Language is concerned . How can i Right Trim all the white spaces of a very long (2000 chars) Charecter string ( from the Right Side ) ? or how can i make a fast Right Trim Function in c,using Binary search kind of fast algorithm ? Offcourse...I can use the classical approach too. like : Start from the right most charecter of the string to the left of the
0
2309
by: William Stacey [MVP] | last post by:
Had a method that got some string info from mp3 tags in N files and serializes this class and deserializes at other side. Works ok except sometimes get chars that choke the XmlSerializer. After some digging, I found XmlSerializer chokes on 0x03 chars. It probably chokes on many others, but this one I found. It serializes ok, but chokes on deserialize on "<Field1>&#x3;</Field1>". So the questions are: 1) Why does serializer produce...
6
2626
by: guy | last post by:
if a string contains surrogate chars (i.e. Unicode characters that consiste of more than 1 char) do functions that use an indexer or a string length into the string e.g. Mid, Len work correctly? guy
21
2314
by: Hitesh | last post by:
Hi, I get path strings from a DB like: \\serverName\C:\FolderName1\FolderName2\example.exe I am writing a script that can give me access to that exe file. But problem is that string is not universal path, I need to add C$. Any idea how I can add $ char in that string. ServerName is not fixed length. It could be any chars length.
6
2355
by: Paulers | last post by:
Hello, I have a string that I am trying to add each char to a datatable row. for example if I have a string that looks like "abcdefg", I would like to break it up into an array of characters so I can do this: myDataTable.Rows.Add(array()) instead of myDataTable.Rows.Add("a","b","c","d","e","f","g")
13
3753
by: Hongyu | last post by:
Hi, I have a datetime char string returned from ctime_r, and it is in the format like ""Wed Jun 30 21:49:08 1993\n\0", which has 26 chars including the last terminate char '\0', and i would like to remove the weekday information that is "Wed" here, and I also would like to replace the spaces char by "_" and also remove the "\n" char. I didn't know how to truncate the string from beginning or replace some chars in a string with another...
0
10346
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8982
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.