473,889 Members | 1,656 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
23 31103
In article <bn**********@i nfo.service.rug .nl>, L.J. Buitinck wrote:
[cut]
char *s;

s = malloc(4);
if (s == NULL) {
/* ... */
}
strcpy(s, "foo");
s = realloc(s, 4+3);
if (s == NULL) {
free(s);
If s is NULL, what use is the free() call?

Hint: Assign the returned value from realloc() to to a temporary pointer.
/* ... */
}
strcat(s, "bar");


/* ... */

free(s);
--
Andreas Kähäri
Nov 13 '05 #11
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.
Was this generated by a Markov chain program?

[snip] /* this is how I use the function */
main(){
char *res1 = ""; // empty string 1
char *res2 = ""; // empty string 2
strAddChar( res1, 'a' );


This produces UB unless strAddChar (re)allocates memory (which it
doesn't). Also, starting a function with 'str' violates the
implementation namespace.

Man strcat, but always make sure you're (allocated) string memory is big
enough to accomodate the new character.

/david

--
"As a scientist, Throckmorton knew that if he were ever to break wind in
the echo chamber, he would never hear the end of it."

Nov 13 '05 #12
David Rubin <fu******@warpm ail.net> wrote:
[...] Also, starting a function with 'str' violates the
implementati on namespace.


But only if followed by a lowercase letter, thus the OP is safe
declaring a function named strAddChar.

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #13
In <Xn************ *************** *****@130.133.1 .4> "Mark A. Odell" <no****@embedde dfw.com> writes:
"Rick" <as******@hotma il.com> wrote in
news:3f******* *************** *@news.xs4all.n l:

NO! You cannot write to res1 or res2. Look up malloc() and use it, then
come back.


Static allocation is perfectly OK for the OP's needs. And dynamic
allocation seems to be above his current C skills.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #14
Rick wrote:

/* 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
Unless you are using a C99 compiler (extremely unlikely), the above
"comment" is a syntax error. Use /* */ comments instead.
*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(){
Make this

int main(void)

'Implicit int' has been removed from the C language. Granted, you are
not using the current version of C, but you might as well get in the
habit if supplying a return type now.
char *res1 = ""; // empty string 1
char *res2 = ""; // empty string 2


Never assign a string literal to a non-const char *. This is only
allowed for historical reasons, and it's never a good idea. You cannot
modify a string literal, so you might as well make it obvious that you
do not intend to modify it by declaring the pointers const:

const char *res1 = "";
const char *res2 = "";

If you make this change, you will find that your program no longer
compiles. This is because it contains an error. The error (attempting to
modify a string literal) was there before, the compiler just wasn't able
to detect it. Once you use the correct type for res1 and res2, it can
detect it.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #15
Kevin Goodsell <us************ *********@never box.com> spoke thus:
Unless you are using a C99 compiler (extremely unlikely), the above
"comment" is a syntax error. Use /* */ comments instead.


Well, it isn't conforming, but he could easily have a compiler that supports
this extension...

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 13 '05 #16
On Thu, 23 Oct 2003 18:38:00 +0200, in comp.lang.c , Irrwahn
Grausewitz <ir*******@free net.de> wrote:
David Rubin <fu******@warpm ail.net> wrote:
[...] Also, starting a function with 'str' violates the
implementatio n namespace.


But only if followed by a lowercase letter, thus the OP is safe
declaring a function named strAddChar.


Safe but dangerous. /He/ might realise the above rule, but the next
maintainer might not. T'is safer just to steer clear entirely of RYO
str.. functions.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #17
Andreas Kahari wrote:
If s is NULL, what use is the free() call?


you're right, excuse me.
char *p, *s;

s = malloc(4);
if (s == NULL) {
/* ... */
}
strcpy(s, "foo");
p = realloc(s, 4+3);
if (p == NULL) {
free(s);
/* ... */
}
s = p;
strcat(s, "bar");
one more alternative: use astring from
http://www.mibsoftware.com/libmib/astring

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

Lars

Nov 13 '05 #18
"Irrwahn Grausewitz" <ir*******@free net.de> wrote:
David Rubin <fu******@warpm ail.net> wrote:
[...] Also, starting a function with 'str' violates the
implementati on namespace.


But only if followed by a lowercase letter, thus the OP is safe
declaring a function named strAddChar.


Only safe if that function is declared static. Otherwise the
external name of the function may conflict with any identifier
starting with 'stradd', since external identifiers need not
be case-sensitive.

C89 3.1.2 Identifiers:
"The implementation may further restrict the significance of
an external name (an identifier that has external linkage)
to six characters and may ignore distinctions of alphabetical
case for such names."

--
Simon.
Nov 13 '05 #19
"Christophe r Benson-Manica" <at***@nospam.c yberspace.org> wrote:
Kevin Goodsell <us************ *********@never box.com> spoke thus:
Unless you are using a C99 compiler (extremely unlikely), the
above "comment" is a syntax error. Use /* */ comments instead.


Well, it isn't conforming, but he could easily have a compiler that
supports this extension...


Such a compiler is not a C compiler, so it is off-topic.

--
Simon.
Nov 13 '05 #20

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

Similar topics

7
3627
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
7422
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
8839
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
6286
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
2320
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
2634
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
2323
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
2360
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
3764
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
9969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9810
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11203
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...
1
10896
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,...
1
7999
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...
0
7151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4650
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
3
3257
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.