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

Home Posts Topics Members FAQ

K&R2, exercise 5.3

PURPOSE: write a pointer version of strcat function.

WHAT I DID: I have 2 implementations of this function. Both compile
and run but 1st one gives some strange results, 2nd is ok. I am unable
to figure out why the 1st implementation gives strange results:
/* A rudimentary strcat function
*
*/
#include <stdio.h>
#include <stdlib.h>
enum MAXSIZE { ARR_SIZE = 1000 };
void my_strcat( char s[], char t[] );
int main()
{
char s[1000] = "Saurabh";
char t[1000] = "Nirkhey\n" ;

printf("\ns --%s\nt --%s\n\n", s, t );
printf("--- concatenating strings -----\n\n");
my_strcat( s, t );
printf("\ns --%s\nt --%s\n\n", s, t );

return EXIT_SUCCESS;
}
void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;

while( *ps++ != '\0' )
{
printf("*ps = %c\n", *ps );
}

while( *pt != '\0' )
{
*ps++ = *pt++;
}

}

=========== OUTPUT ===============

/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra 5-3.c
/home/arnuld/programs/C $ ./a.out

s --Saurabh
t --Nirkhey
--- concatenating strings -----

*ps = a
*ps = u
*ps = r
*ps = a
*ps = b
*ps = h
*ps = ^@

==2nd version's strcat function:

void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;

while( *ps != '\0' )
{
printf("*ps = %c\n", *ps );
ps++;
}

while( *pt != '\0' )
{
*ps++ = *pt++;
}

}

============ OUPUT ============
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra 5-3.c
/home/arnuld/programs/C $ ./a.out

s --Saurabh
t --Nirkhey
--- concatenating strings -----

*ps = S
*ps = a
*ps = u
*ps = r
*ps = a
*ps = b
*ps = h

s --SaurabhNirkhey

t --Nirkhey
/home/arnuld/programs/C $


-- http://lispmachine.wordpress.com/

Please remove capital 'V's when you reply to me via e-mail.

Apr 8 '08 #1
3 1518
arnuld schrieb:
PURPOSE: write a pointer version of strcat function.

WHAT I DID: I have 2 implementations of this function. Both compile
and run but 1st one gives some strange results, 2nd is ok. I am unable
to figure out why the 1st implementation gives strange results:
[SNIP]
void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;
Here the pointer ps gets incremented, regardless of the result of
the comparison. That way, in the loop you print always the character
*following* the one ps pointed to when the loop condition was last
checked; the output of your debug print statements should have been
a hint...
while( *ps++ != '\0' )
{
printf("*ps = %c\n", *ps );
}
At this point, ps points one character *beyond* the terminating null
character in s. Effectively, you are now going to copy the contents
of t to "dead"[1] space in the array s:
while( *pt != '\0' )
{
*ps++ = *pt++;
}
[SNIP]
==2nd version's strcat function:
[SNIP]

This time you got it right: increment ps only if the loop condition is
true (and debug-print the character ps points to *before* incrementing
the pointer).
while( *ps != '\0' )
{
printf("*ps = %c\n", *ps );
ps++;
}
[SNIP]

Alternatively, you could have used a for loop, of course:

for ( ps = s; *ps != '\0'; ++ps )
/* skip, or whatever */;

[1] In the sense of: "will be ignored, when s is treated as a string".
Best regards
--
Irrwahn Grausewitz [ir*******@freen et.de]

Apr 8 '08 #2
arnuld wrote:
[problem with strcat implementation]
[first version, buggy:]
void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;

while( *ps++ != '\0' )
{
printf("*ps = %c\n", *ps );
}

while( *pt != '\0' )
{
*ps++ = *pt++;
}

}

==2nd version's strcat function:
[working]
>
void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;

while( *ps != '\0' )
{
printf("*ps = %c\n", *ps );
ps++;
}

while( *pt != '\0' )
{
*ps++ = *pt++;
}

}
You have correctly identified the location of the problem. Specifically,
the problem is the following while loop in the first version:

while (*ps++ != '\0')

This says "Check whether *ps equals '\0', and afterwards, increment ps".
Note that ps is incremented whether or not the equality test succeeds.

Look at the printf() output. By the time printf() prints *ps, ps has
already been incremented. This is why you never output the first
character of the string.

Similarly, when you detect a '\0' character, you then increment ps past
that character. As a result, the '\0' is never overwritten with a
character from pt; the contents of the char array after the call are as
follows:

"Saurabh\0Nirkh ey\n"

The '\0' part-way through a char array means "end of string", so the
printf() call in main() won't print anything beyond that point.

I hope this helps you understand why your first version doesn't work but
your second version does.
Apr 8 '08 #3
Groovy hepcat arnuld was jivin' in comp.lang.c on Tue, 8 Apr 2008 8:04
pm. It's a cool scene! Dig it.
PURPOSE: write a pointer version of strcat function.

WHAT I DID: I have 2 implementations of this function. Both compile
and run but 1st one gives some strange results, 2nd is ok. I am unable
to figure out why the 1st implementation gives strange results:
In addition to the problems pointed out by other people, you have
another serious bug in both versions of this.
void my_strcat( char s[], char t[] )
{
char *ps, *pt;

ps = s;
pt = t;
Why create more variables? s and t are both pointers. I know they look
like arrays, somewhat, but they're pointers; and they're local to the
function. You don't need to keep their initial values for anything, so
you can use these instead of ps and pt.
But that's just a matter of style more than anything else. It's not
the source of the problem I mentioned.
while( *ps++ != '\0' )
Problem here already mentioned by others.
{
printf("*ps = %c\n", *ps );
}

while( *pt != '\0' )
{
*ps++ = *pt++;
}
Here's the other problem. You copy every character pointed at by pt to
the corresponding location indicated by ps. However, you don't
terminate the resulting string with a null character. This is a serious
problem that just happens to have eluded you by sheer luck. Whether
that luck is good or bad depends on your outlook. Do you consider it
good luck to have a serious bug lurking in code, unbeknownst to the
coder, waiting to pounce and bring down a billion dollar client's
entire network when he least expects it, costing billions of dollars to
fix? (I know, I know. This code is just a small program whose purpose
is to educate you on the ways of C. But in future, when you use C in
the workplace, errors like this are easy to miss. So you need to learn
about these things now, so you'll know what to look for then.)
Actually, the reason you've not seen this problem is that your arrays
in main() were initialised, which sets the entire contents of the
array. Array elements beyond the length of the initialiser are filled
with the value 0. So your concatenated string just happens to be null
terminated. But as a general replacement for strcat(), this function is
a disaster waiting to happen.
You need to explicitly terminate the string, which is as simple as
this:

*ps = '0';
}
The other version of your function has the same problem as I have
mentioned here.

--
Dig the sig!

----------- Peter 'Shaggy' Haywood ------------
Ain't I'm a dawg!!
Jun 27 '08 #4

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

Similar topics

12
2153
by: Chris Readle | last post by:
Ok, I've just recently finished a beginning C class and now I'm working through K&R2 (alongside the C99 standard) to *really* learn C. So anyway, I'm working on an exercise in chapter one which give me strange behavior. Here is the code I've written: /****************************************************************************** * K&R2...
16
2261
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of blanks as a single one */ int main() { int c;
2
2281
by: arnuld | last post by:
there is a solution on "clc-wiki" for exercise 1.17 of K&R2: http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_17 i see this uses pointers whereas K&R2 have not discussed pointers yet. i have created a solution myself by modifying the example programme of section 1.19. i tried to find the source-code of K&R2 using Google. i...
8
4750
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. --------------------------------- PROGRAMME -------------------------------- /* K&R2 section 1.9 exercise 1.19
4
1555
by: arnuld | last post by:
as i said, i have restarted the book because i overlooked some material. i want to have some comments/views on this solution. it runs fine, BTW. ------------------ PROGRAMME -------------- /* K&R2 section 1.5.3, exercise 1-8 write a programme to count blanks, tabs and newlines */
16
1790
by: arnuld | last post by:
i have created solution which compiles and runs without any error/ warning but it does not work. i am not able to understand why. i thought it is good to post my code here for correction before looking at CLC-Wiki for K&R2 solutions: --------------- PROGRAMME ------------ /* K&R2 section 1.5.3, exercise 1-9 STATEMENT: write a programme...
19
2385
by: arnuld | last post by:
this programme runs without any error but it does not do what i want it to do: ------------- PROGRAMME -------------- /* K&R2, section 1.6 Arrays; Exercise 1-13. STATEMENT: Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical
5
2910
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any compile-error BUT it has a semantic BUG: what i WANT: I want it to produce a "horizontal histogram" which tells how many characters were in the 1st...
16
1718
by: arnuld | last post by:
i am not able to make it work. it compiles without any error but does not work: what i WANTED: 1.) 1st we will take the input in to an array. (calling "getline" in "main") 2.) we will print that input array on terminal. (in "main") 3.) we will reverse the array. (calling "reverse" in "main") 4.) we will print that reversed array. (in...
88
3705
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without invoking undefined behaviour triggered by overflow? Remember that the constants in limits.h cannot be used.
0
7876
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...
0
7804
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...
0
8156
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. ...
0
8310
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...
0
8180
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...
0
6563
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...
0
3809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3832
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2307
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

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.