I am just learning C and got to the point of pointers. I wrote a method which should concate two char pointers and I got a strange behavior I just cant explain to myself nor did I find an answer on it, so maybe you can help!
So I don't understand why stringcat
and stringptr
point to different addresses, namely ones that are 8 Byte appart. Secondly, I dont understand why I cannot use stringcat
in the two while-loops on the bottom. I just dont get any output. Also if I use stringptr[0]
in the last printf
, there won't be any output.
Thank you for your help in advance!
Edit: This code works, I just don't understand why I cant use stringcat
on bottom.
Edit2: Noticed some * got missing while copy pasting, so I added them!
char stringcat(const char str1, const char* str2){
char *ptr1 = str1;
char *ptr2 = str2;
int count = 0;
while(*ptr1 != '\0'){
count++;
ptr1++;
}
while(*ptr2 != '\0'){
count++;
ptr2++;
}
char *stringcat = malloc((count+1)*sizeof(char));
char *stringptr = stringcat;
printf("%d %d", &stringcat, &stringptr);
ptr1 = str1;
ptr2 = str2;
while(*ptr1 != '\0' && (stringptr++ = ptr1++));
printf("%c", stringcat[0]);
while(*stringptr++ = *ptr2++);
return stringcat;
}