Thursday, August 23, 2007

C/C++ Lab - Optimising String Concatenation

We had C Lab yesterday, our teacher is really good, here is some code to concatenate two strings, super efficient ::

char *a="Hello";
char *b="World";
char *c;
c=a;
while(*a)
a++;
while(*a++=*b++);
printf("%s",c);

Output ::

HelloWorld

The algorithm has its roots in Data Structures, really cool !

4 comments:

Royal said...

The code will crash. No allocation done for the concatenated string.

Tikna said...

Have you checked the code ? Works 100% correct in Turbo C/C++

I assume these languages automatically assign memory blocks when i write

char *var="data"

Otherwise a NULL pointer assignment error would have come, but it doesnt.

I remember Visual J++ also did the same thing.

Tikna said...

Ok i got what you want to say, a possible turnaround is to keep string 1 with the size of max length of concatenated string.

rohit said...

you mean workaround?