472,365 Members | 1,277 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,365 software developers and data experts.

Efficient strcat implementation.

Hi,

I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.

Please help.

Thanks a lot
Jun 27 '08 #1
28 3755
Mahesh wrote:
Hi,

I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.

Please help.
Show us what you have.

--
Ian Collins.
Jun 27 '08 #2
Mahesh wrote:
I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.
Just use the strcat your implementation provides for you. On any decent
implementation it is pretty unlikely that you can come up with something
more efficient.

Bye, Jojo
Jun 27 '08 #3
Mahesh <mm*****@gmail.comwrites:
I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.
One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:

----------------------------------------------------------------------

Programmers using the `strcat' or `wcscat' function (or the
following `strncat' or `wcsncar' functions for that matter) can easily
be recognized as lazy and reckless. In almost all situations the
lengths of the participating strings are known (it better should be
since how can one otherwise ensure the allocated size of the buffer is
sufficient?) Or at least, one could know them if one keeps track of the
results of the various function calls. But then it is very inefficient
to use `strcat'/`wcscat'. A lot of time is wasted finding the end of
the destination string so that the actual copying can start. This is a
common example:

/* This function concatenates arbitrarily many strings. The last
parameter must be `NULL'. */
char *
concat (const char *str, ...)
{
va_list ap, ap2;
size_t total = 1;
const char *s;
char *result;

va_start (ap, str);
/* Actually `va_copy', but this is the name more gcc versions
understand. */
__va_copy (ap2, ap);

/* Determine how much space we need. */
for (s = str; s != NULL; s = va_arg (ap, const char *))
total += strlen (s);

va_end (ap);

result = (char *) malloc (total);
if (result != NULL)
{
result[0] = '\0';

/* Copy the strings. */
for (s = str; s != NULL; s = va_arg (ap2, const char *))
strcat (result, s);
}

va_end (ap2);

return result;
}

This looks quite simple, especially the second loop where the strings
are actually copied. But these innocent lines hide a major performance
penalty. Just imagine that ten strings of 100 bytes each have to be
concatenated. For the second string we search the already stored 100
bytes for the end of the string so that we can append the next string.
For all strings in total the comparisons necessary to find the end of
the intermediate results sums up to 5500! If we combine the copying
with the search for the allocation we can write this function more
efficient:

char *
concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);

if (result != NULL)
{
char *newp;
char *wp;

va_start (ap, str);

wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);

/* Resize the allocated memory if necessary. */
if (wp + len + 1 result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;
}

wp = mempcpy (wp, s, len);
}

/* Terminate the result string. */
*wp++ = '\0';

/* Resize memory to the optimal size. */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;

va_end (ap);
}

return result;
}

With a bit more knowledge about the input strings one could fine-tune
the memory allocation. The difference we are pointing to here is that
we don't use `strcat' anymore. We always keep track of the length of
the current intermediate result so we can safe us the search for the
end of the string and use `mempcpy'. Please note that we also don't
use `stpcpy' which might seem more natural since we handle with
strings. But this is not necessary since we already know the length of
the string and therefore can use the faster memory copying function.
The example would work for wide characters the same way.

Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code cannot
be rewritten to take advantage of already calculated results. Again: it
is almost always unnecessary to use `strcat'.

--
"Some people *are* arrogant, and others read the FAQ."
--Chris Dollin
Jun 27 '08 #4
Ben Pfaff <bl*@cs.stanford.eduwrites:
Mahesh <mm*****@gmail.comwrites:
>I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:
<snip>
char *
concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);

if (result != NULL)
{
char *newp;
char *wp;

va_start (ap, str);

wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);

/* Resize the allocated memory if necessary. */
if (wp + len + 1 result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;
It is probably worth pointing out (since there was a thread about this
recently) that the above should really use something like:

size_t offset = wp - result;
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + offset;
result = newp;

to avoid the UB of using the old pointer.
}

wp = mempcpy (wp, s, len);
}

/* Terminate the result string. */
*wp++ = '\0';

/* Resize memory to the optimal size. */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;

va_end (ap);
}

return result;
}
--
Ben.
Jun 27 '08 #5
Ben Bacarisse <be********@bsb.me.ukwrites:
Ben Pfaff <bl*@cs.stanford.eduwrites:
>Mahesh <mm*****@gmail.comwrites:
>>I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:
<snip>
> char *
concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);

if (result != NULL)
{
char *newp;
char *wp;

va_start (ap, str);

wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);

/* Resize the allocated memory if necessary. */
if (wp + len + 1 result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;

It is probably worth pointing out (since there was a thread about this
recently) that the above should really use something like:

size_t offset = wp - result;
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
Why do you cast the realloc? Is it different in that respect from
malloc?
Jun 27 '08 #6
Richard <de***@gmail.comwrites:
Ben Bacarisse <be********@bsb.me.ukwrites:
>Ben Pfaff <bl*@cs.stanford.eduwrites:
>>But here is what the GNU libc manual says about strcat:
<snip>
<snip>
>> char *result = (char *) malloc (allocated);
newp = (char *) realloc (result, allocated);
<snip>
>
Why do you cast the realloc?
I don't. The code's original author did for reasons one can only
speculate on.
Is it different in that respect from malloc?
No (and they also did it for the malloc call).

--
Ben.
Jun 27 '08 #7
Ben Pfaff wrote:
Mahesh <mm*****@gmail.comwrites:
>I am looking for efficient string cancatination c code. I did it using
ptr [using default method] but my code i think is not efficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:

----------------------------------------------------------------------

Programmers using the `strcat' or `wcscat' function (or the
following `strncat' or `wcsncar' functions for that matter) can easily
be recognized as lazy and reckless. In almost all situations the
lengths of the participating strings are known (it better should be
since how can one otherwise ensure the allocated size of the buffer is
sufficient?) Or at least, one could know them if one keeps track of the
results of the various function calls. But then it is very inefficient
to use `strcat'/`wcscat'. A lot of time is wasted finding the end of
the destination string so that the actual copying can start. This is a
common example:

/* This function concatenates arbitrarily many strings. The last
parameter must be `NULL'. */
char *
concat (const char *str, ...)
{
va_list ap, ap2;
size_t total = 1;
const char *s;
char *result;

va_start (ap, str);
/* Actually `va_copy', but this is the name more gcc versions
understand. */
__va_copy (ap2, ap);

/* Determine how much space we need. */
for (s = str; s != NULL; s = va_arg (ap, const char *))
total += strlen (s);

va_end (ap);

result = (char *) malloc (total);
if (result != NULL)
{
result[0] = '\0';

/* Copy the strings. */
for (s = str; s != NULL; s = va_arg (ap2, const char *))
strcat (result, s);
}

va_end (ap2);

return result;
}

This looks quite simple, especially the second loop where the strings
are actually copied. But these innocent lines hide a major performance
penalty. Just imagine that ten strings of 100 bytes each have to be
concatenated. For the second string we search the already stored 100
bytes for the end of the string so that we can append the next string.
For all strings in total the comparisons necessary to find the end of
the intermediate results sums up to 5500! If we combine the copying
with the search for the allocation we can write this function more
efficient:

char *
concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);

if (result != NULL)
{
char *newp;
char *wp;

va_start (ap, str);

wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);

/* Resize the allocated memory if necessary. */
if (wp + len + 1 result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;
}

wp = mempcpy (wp, s, len);
}

/* Terminate the result string. */
*wp++ = '\0';

/* Resize memory to the optimal size. */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;

va_end (ap);
}

return result;
}

With a bit more knowledge about the input strings one could fine-tune
the memory allocation. The difference we are pointing to here is that
we don't use `strcat' anymore. We always keep track of the length of
the current intermediate result so we can safe us the search for the
end of the string and use `mempcpy'. Please note that we also don't
use `stpcpy' which might seem more natural since we handle with
strings. But this is not necessary since we already know the length of
the string and therefore can use the faster memory copying function.
The example would work for wide characters the same way.

Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code cannot
be rewritten to take advantage of already calculated results. Again: it
is almost always unnecessary to use `strcat'.
The problem is not a lazy programmer but
zero terminated strings!

Using counted strings is much more efficient
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Jun 27 '08 #8
jacob wrote:
) The problem is not a lazy programmer but
) zero terminated strings!
)
) Using counted strings is much more efficient

In some cases, yes.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Jun 27 '08 #9
Richard <de***@gmail.comwrites:
Ben Bacarisse <be********@bsb.me.ukwrites:
>Ben Pfaff <bl*@cs.stanford.eduwrites:
>> newp = (char *) realloc (result, allocated);

It is probably worth pointing out (since there was a thread about this
recently) that the above should really use something like:

size_t offset = wp - result;
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);

Why do you cast the realloc? Is it different in that respect from
malloc?
I don't recommend casting the result of realloc() or malloc(),
for the same reasons. I assume that Ben B. cast the result
because the code in the GNU C library manual did so. I don't
know whether the authors of that code had a good reason to do so;
I would guess not.
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x11f6},*p
=b,i=24;for(;p+=!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
Jun 27 '08 #10
Ben Pfaff wrote:
>
.... snip ...
>
Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code
cannot be rewritten to take advantage of already calculated
results. Again: it is almost always unnecessary to use `strcat'.
Besides which the use of strlcat and strlcpy is much easier and
more accurate. These are non-standard functions. One public
domain implementation, with source and documentation, in standard
C, is available at:

<http://cbfalconer.home.att.net/download/>

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #11
CBFalconer <cb********@yahoo.comwrites:
Ben Pfaff wrote:
>Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code
cannot be rewritten to take advantage of already calculated
results. Again: it is almost always unnecessary to use `strcat'.
I was quoting the GNU C library manual when I wrote that.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Jun 27 '08 #12
On Apr 22, 4:10 am, Ian Collins <ian-n...@hotmail.comwrote:
Maheshwrote:
Hi,
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.
Please help.

Show us what you have.

--
Ian Collins.
here is my code: its very very simple prog.

#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));
*(temp++) = ' ';
while((*temp++ = *dest++));
printf("Final Result = %s \n", temp1);
}
Jun 27 '08 #13
On Apr 22, 11:34 am, Ben Pfaff <b...@cs.stanford.eduwrote:
Mahesh<mmp....@gmail.comwrites:
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:

----------------------------------------------------------------------

Programmers using the `strcat' or `wcscat' function (or the
following `strncat' or `wcsncar' functions for that matter) can easily
be recognized as lazy and reckless. In almost all situations the
lengths of the participating strings are known (it better should be
since how can one otherwise ensure the allocated size of the buffer is
sufficient?) Or at least, one could know them if one keeps track of the
results of the various function calls. But then it is very inefficient
to use `strcat'/`wcscat'. A lot of time is wasted finding the end of
the destinationstringso that the actual copying can start. This is a
common example:

/* This function concatenates arbitrarily many strings. The last
parameter must be `NULL'. */
char *
concat (const char *str, ...)
{
va_list ap, ap2;
size_t total = 1;
const char *s;
char *result;

va_start (ap, str);
/* Actually `va_copy', but this is the name more gcc versions
understand. */
__va_copy (ap2, ap);

/* Determine how much space we need. */
for (s = str; s != NULL; s = va_arg (ap, const char *))
total += strlen (s);

va_end (ap);

result = (char *) malloc (total);
if (result != NULL)
{
result[0] = '\0';

/* Copy the strings. */
for (s = str; s != NULL; s = va_arg (ap2, const char *))
strcat (result, s);
}

va_end (ap2);

return result;
}

This looks quite simple, especially the second loop where the strings
are actually copied. But these innocent lines hide a major performance
penalty. Just imagine that ten strings of 100 bytes each have to be
concatenated. For the secondstringwe search the already stored 100
bytes for the end of thestringso that we can append the nextstring.
For all strings in total the comparisons necessary to find the end of
the intermediate results sums up to 5500! If we combine the copying
with the search for the allocation we can write this function moreefficient:

char *
concat (const char *str, ...)
{
va_list ap;
size_t allocated = 100;
char *result = (char *) malloc (allocated);

if (result != NULL)
{
char *newp;
char *wp;

va_start (ap, str);

wp = result;
for (s = str; s != NULL; s = va_arg (ap, const char *))
{
size_t len = strlen (s);

/* Resize the allocated memory if necessary. */
if (wp + len + 1 result + allocated)
{
allocated = (allocated + len) * 2;
newp = (char *) realloc (result, allocated);
if (newp == NULL)
{
free (result);
return NULL;
}
wp = newp + (wp - result);
result = newp;
}

wp = mempcpy (wp, s, len);
}

/* Terminate the resultstring. */
*wp++ = '\0';

/* Resize memory to the optimal size. */
newp = realloc (result, wp - result);
if (newp != NULL)
result = newp;

va_end (ap);
}

return result;
}

With a bit more knowledge about the input strings one could fine-tune
the memory allocation. The difference we are pointing to here is that
we don't use `strcat' anymore. We always keep track of the length of
the current intermediate result so we can safe us the search for the
end of thestringand use `mempcpy'. Please note that we also don't
use `stpcpy' which might seem more natural since we handle with
strings. But this is not necessary since we already know the length of
thestringand therefore can use the faster memory copying function.
The example would work for wide characters the same way.

Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code cannot
be rewritten to take advantage of already calculated results. Again: it
is almost always unnecessary to use `strcat'.

--
"Some people *are* arrogant, and others read the FAQ."
--Chris Dollin
Thanks a lot Chris and all who assisted me in this regard. Much Glad
about response.
Jun 27 '08 #14
Mahesh wrote:
On Apr 22, 4:10 am, Ian Collins <ian-n...@hotmail.comwrote:
>Maheshwrote:
Hi,
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.
Please help.

Show us what you have.

--
Ian Collins.

here is my code: its very very simple prog.

#include <stdio.h>
#include <malloc.h>
This is not a standardised header. Malloc and it's related functions are
defined, as per the standard, in stdlib.h. So the above line is
unnecessary on any ANSI conforming compiler; indeed it's non-portable.
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);
This is not what you want. Firstly in C you don't need to cast the
return value as there is implicit conversion between void * and any
other object pointer type. Secondly you want strlen instead of sizeof.
sizeof will only give you the size of the pointers src and dest.

temp = calloc(strlen(src)+strlen(dest)+1, 1);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));
The first test is unnecessary. Or you could simply use strcpy or memcpy
for this purpose. If you do remove the check against '\0' then don't
forget to decrement temp by one after the loop is done.
*(temp++) = ' ';
Why?
while((*temp++ = *dest++));
printf("Final Result = %s \n", temp1);
}
Jun 27 '08 #15
Mahesh <mm*****@gmail.comwrites:
On Apr 22, 11:34 am, Ben Pfaff <b...@cs.stanford.eduwrote:
>Mahesh<mmp....@gmail.comwrites:
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:

Thanks a lot Chris and all who assisted me in this regard.
"Chris"? My name is Ben, thanks.
--
Ben Pfaff
http://benpfaff.org
Jun 27 '08 #16
Mahesh wrote:
>
.... snip ...
>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));
*(temp++) = ' ';
while((*temp++ = *dest++));
printf("Final Result = %s \n", temp1);
}
Besides the errors santosh has described, main returns an int. Do
so. You have 0, EXIT_SUCCESS, and EXIT_FAILURE values available.
The EXIT* values are only available if you #include <stdlib.h>.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #17
On Apr 23, 10:51*am, santosh <santosh....@gmail.comwrote:
Mahesh wrote:
On Apr 22, 4:10 am, Ian Collins <ian-n...@hotmail.comwrote:
Maheshwrote:
Hi,
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.
Please help.
Show us what you have.
--
Ian Collins.
here is my code: its very very simple prog.
#include <stdio.h>
#include <malloc.h>

This is not a standardised header. Malloc and it's related functions are
defined, as per the standard, in stdlib.h. So the above line is
unnecessary on any ANSI conforming compiler; indeed it's non-portable.
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);

This is not what you want. Firstly in C you don't need to cast the
return value as there is implicit conversion between void * and any
other object pointer type. Secondly you want strlen instead of sizeof.
sizeof will only give you the size of the pointers src and dest.

* temp = calloc(strlen(src)+strlen(dest)+1, 1);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));

The first test is unnecessary. Or you could simply use strcpy or memcpy
for this purpose. If you do remove the check against '\0' then don't
forget to decrement temp by one after the loop is done.
What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)
Jun 27 '08 #18
On Wed, 23 Apr 2008 21:19:32 -0700, Chad wrote:

What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)

nothing, of course

:)

I prefer the 1st style but if you are copying arrays I better use strcpy.
--
http://lispmachine.wordpress.com/
my email ID is at the above address

Jun 27 '08 #19
Chad wrote:
On Apr 23, 10:51*am, santosh <santosh....@gmail.comwrote:
>Mahesh wrote:
On Apr 22, 4:10 am, Ian Collins <ian-n...@hotmail.comwrote:
Maheshwrote:
Hi,
I am looking forefficientstringcancatination c code. I did it
using ptr [using default method] but my code i think is
notefficient.
Please help.
>Show us what you have.
>--
Ian Collins.
here is my code: its very very simple prog.
#include <stdio.h>
#include <malloc.h>

This is not a standardised header. Malloc and it's related functions
are defined, as per the standard, in stdlib.h. So the above line is
unnecessary on any ANSI conforming compiler; indeed it's
non-portable.
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);

This is not what you want. Firstly in C you don't need to cast the
return value as there is implicit conversion between void * and any
other object pointer type. Secondly you want strlen instead of
sizeof. sizeof will only give you the size of the pointers src and
dest.

temp = calloc(strlen(src)+strlen(dest)+1, 1);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));

The first test is unnecessary. Or you could simply use strcpy or
memcpy for this purpose. If you do remove the check against '\0' then
don't forget to decrement temp by one after the loop is done.

What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)
After the while loop is done each pointer will point to one past the end
of the zero element, while they would point to the zero element in the
case of the for loop.

Jun 27 '08 #20
arnuld wrote:
>On Wed, 23 Apr 2008 21:19:32 -0700, Chad wrote:

>What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)


nothing, of course

:)

I prefer the 1st style but if you are copying arrays I better use
strcpy.
For plain arrays memcpy might be even better, reserving strcpy for
strings.

Jun 27 '08 #21
Ben Pfaff wrote:
Mahesh <mm*****@gmail.comwrites:
>On Apr 22, 11:34 am, Ben Pfaff <b...@cs.stanford.eduwrote:
>>Mahesh<mmp....@gmail.comwrites:
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:

Thanks a lot Chris and all who assisted me in this regard.

"Chris"? My name is Ben, thanks.
Your signature had a quote from me; Mahesh must have confused
your attribution-to-me with a this-is-my-name.

(fx:blushing-hedgehog)

--
"It was the first really clever thing the King had /Alice in Wonderland/
said that day."

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jun 27 '08 #22
Santosh,

*(temp++) = ' ' this is for inserting space between words so it
looks neat in final result.

Thanks :).
santosh wrote:
Mahesh wrote:
On Apr 22, 4:10 am, Ian Collins <ian-n...@hotmail.comwrote:
Maheshwrote:
Hi,

I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.

Please help.

Show us what you have.

--
Ian Collins.
here is my code: its very very simple prog.

#include <stdio.h>
#include <malloc.h>

This is not a standardised header. Malloc and it's related functions are
defined, as per the standard, in stdlib.h. So the above line is
unnecessary on any ANSI conforming compiler; indeed it's non-portable.
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);

This is not what you want. Firstly in C you don't need to cast the
return value as there is implicit conversion between void * and any
other object pointer type. Secondly you want strlen instead of sizeof.
sizeof will only give you the size of the pointers src and dest.

temp = calloc(strlen(src)+strlen(dest)+1, 1);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));

The first test is unnecessary. Or you could simply use strcpy or memcpy
for this purpose. If you do remove the check against '\0' then don't
forget to decrement temp by one after the loop is done.
*(temp++) = ' ';

Why?
while((*temp++ = *dest++));
printf("Final Result = %s \n", temp1);
}
Jun 27 '08 #23
Hey Ben,

Sory about that. But thanks for your great help :).

Ben Pfaff wrote:
Mahesh <mm*****@gmail.comwrites:
On Apr 22, 11:34 am, Ben Pfaff <b...@cs.stanford.eduwrote:
Mahesh<mmp....@gmail.comwrites:
I am looking forefficientstringcancatination c code. I did it using
ptr [using default method] but my code i think is notefficient.

One possible implementation:
strcpy(strchr(dst, '\0'), src);

But here is what the GNU libc manual says about strcat:
Thanks a lot Chris and all who assisted me in this regard.

"Chris"? My name is Ben, thanks.
--
Ben Pfaff
http://benpfaff.org
Jun 27 '08 #24
Mahesh wrote:

TOP-POST REFORMATTED.
santosh wrote:
>Mahesh wrote:
[ ... ]
here is my code: its very very simple prog.

#include <stdio.h>
#include <malloc.h>

This is not a standardised header. Malloc and it's related functions
are defined, as per the standard, in stdlib.h. So the above line is
unnecessary on any ANSI conforming compiler; indeed it's
non-portable.
#include <string.h>
int main(void)
{
char *src = "String";
char *dest = "Concatenation Code";
char *temp;
char *temp1;
temp = (char*)calloc(1, sizeof(src)+sizeof(dest)+2);

This is not what you want. Firstly in C you don't need to cast the
return value as there is implicit conversion between void * and any
other object pointer type. Secondly you want strlen instead of
sizeof. sizeof will only give you the size of the pointers src and
dest.

temp = calloc(strlen(src)+strlen(dest)+1, 1);
temp1 = temp;
while(*src != '\0' && (*temp++ = *src++));

The first test is unnecessary. Or you could simply use strcpy or
memcpy for this purpose. If you do remove the check against '\0' then
don't forget to decrement temp by one after the loop is done.
*(temp++) = ' ';

Why?
while((*temp++ = *dest++));
printf("Final Result = %s \n", temp1);
}

Santosh,

*(temp++) = ' ' this is for inserting space between words so it
looks neat in final result.

Thanks :).
Okay, but usually it's not the job of a library function like strcat to
change the characters in the strings. Sometimes you may want a space
and sometimes you may not (as there may already be a space in one of
the strings).

Jun 27 '08 #25
On Thu, 24 Apr 2008 15:52:45 +0500, arnuld <No****@NoPain.comwrote:
>On Wed, 23 Apr 2008 21:19:32 -0700, Chad wrote:

>What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)


nothing, of course
Did you mean that since both are missing the terminal semicolon they
would both wreck havoc on whatever the next statement happened to be?
Or did you not recognize that both pointers in the for loop end up
pointing one byte past where they end up in the while loop?
Remove del for email
Jun 27 '08 #26
Barry Schwarz <sc******@dqel.comwrites:
On Thu, 24 Apr 2008 15:52:45 +0500, arnuld <No****@NoPain.comwrote:
>>On Wed, 23 Apr 2008 21:19:32 -0700, Chad wrote:

>>What would be the difference between

while(*temp++ = *src++)

vs

for( ; *temp = *src; temp++, src++)


nothing, of course
Did you mean that since both are missing the terminal semicolon they
would both wreck havoc on whatever the next statement happened to
be?
Good point.
Or did you not recognize that both pointers in the for loop end up
pointing one byte past where they end up in the while loop?
It's the other way round, as I am sure you know.

--
Ben.
Jun 27 '08 #27
Mahesh wrote: *** and top-posted. Fixed. ***
Ben Pfaff wrote:
>Mahesh <mm*****@gmail.comwrites:
.... snip ...
>>
>>Thanks a lot Chris and all who assisted me in this regard.

"Chris"? My name is Ben, thanks.

Sory about that. But thanks for your great help :).
Please do not top-post. Your answer belongs after (or intermixed
with) the quoted material to which you reply, after snipping all
irrelevant material. I fixed this one. See the following links:

<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html>
<http://www.netmeister.org/news/learn2quote.html>
<http://cfaj.freeshell.org/google/ (taming google)
<http://members.fortunecity.com/nnqweb/ (newusers)

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #28
CBFalconer <cb********@yahoo.comwrites:
Mahesh wrote: *** and top-posted. Fixed. ***
>Ben Pfaff wrote:
>>Mahesh <mm*****@gmail.comwrites:
... snip ...
>>>
Thanks a lot Chris and all who assisted me in this regard.

"Chris"? My name is Ben, thanks.

Sory about that. But thanks for your great help :).

Please do not top-post. Your answer belongs after (or intermixed
with) the quoted material to which you reply, after snipping all
irrelevant material. I fixed this one. See the following links:

<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html>
<http://www.netmeister.org/news/learn2quote.html>
<http://cfaj.freeshell.org/google/ (taming google)
<http://members.fortunecity.com/nnqweb/ (newusers)
Please stop breaking the rules with your signature.

The recommended length is 4 lines.

Your constant net nannying is tedious to the extreme. If you have nothing
to offer then please do not post. This is not your news group and your
constant off topic rambles and incorrect advice is liable to be a
detriment to the charter which is to discuss the C programming language.
Jun 27 '08 #29

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

Similar topics

5
by: Kevin C. | last post by:
Never mind my last post about pointer subtraction, I traced the code and found the offender to be strcat. char call = "del "; system(strcat(strcat(call, del->table_name), ".tab")); After this...
12
by: s99999999s2003 | last post by:
hi I have a file which is very large eg over 200Mb , and i am going to use python to code a "tail" command to get the last few lines of the file. What is a good algorithm for this type of task...
15
by: Oswald Kluge | last post by:
Dear Reader, I'm trying to implement the following short algorithm: Given a number n, remove all the multiples of n from the list of non-negative numbers from 1 through a limit k. My...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.