jaferic jaferic - 1 year ago 90
C Question

Learning C pointers i cant figure out why this is not working (K&R excercise 5-2)

Ok, so i am actually going through K&R C book (I know it is old and it has a lot of outdated stuff specially on the security side but i am just trying to do the excercises) Ive been playing with excercise 5-2 where i need to implement my own strcat with pointers. My code is the following:

#include <stdio.h>
#include <stdlib.h>

char *Strcat(char *string1, const char *string2);

int main(void){
char string1[100]="hello";
char string2[100]="1234";
return 0;

char *Strcat (char *string1, const char *string2){
int i=0;
char *temp=string1;
while(*string1){// move the pointer to find the end of the string
while(*string1++=*string2++)//copy string 2 at the end of string 1
puts(string1);//print string 1 concatenated with string 2
return temp;//send back temp pointing to string1 for printing

My question is, why if i try to print string1 inside the function it just prints blanks? shouldnt it print the whole string? If i print temp it is fine as it runs the print function until it finds a '\0' but when trying with string 1 it seems it is positioned in '\0' shouldnt the pointer go back to string1[0] position?. It is probably something simple but i cant figure out why this is happening...

Any help is appreciated! thanks!!!

Answer Source

++string1 has the effect on the variable equivalent to string1 = string1 + 1. So by the time you try to print string1 it no longer points to the start of the original string.