Pointer concatenation using function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pointer concatenation using function

https://code.sololearn.com/ca3A24A4a3A1 Am I doing this right? from the output why G is showing like double times after the function being called?

26th Apr 2021, 8:21 PM
Ramisa Fariha
Ramisa Fariha - avatar
11 Answers
+ 2
So in the end, the value of `ss` should be "ZZZZZZZZZZABCDEFG" right? You can do this easily using the function strncpy() from the <string.h> header. https://code.sololearn.com/cdk0zB5E4l7p/?ref=app
26th Apr 2021, 9:02 PM
XXX
XXX - avatar
+ 2
@Ipang int m=len(ss)+len(s)+1 then char ss[m] like this? @XXX I have to do this according to the question otherwise I would have used string
26th Apr 2021, 9:14 PM
Ramisa Fariha
Ramisa Fariha - avatar
+ 2
Martin, Thanks for telling, but honestly, it's confusing that they wrote "first n bytes" when they didn't mean to limit the number of copied bytes, but rather just copy the entire string.
27th Apr 2021, 1:02 AM
Ipang
+ 1
The question is: 7.10 Write the following function that copies the first n bytes beginning with *s2 into the bytes beginning at the location of the first occurrence of the null character’\0’ after *s1, where n is the number of bytes that s2 has to be incremented before it points to the null character '\0': void cat(char* s1,const char* s2)
26th Apr 2021, 8:21 PM
Ramisa Fariha
Ramisa Fariha - avatar
+ 1
Your code appears to be changing contents of variable <s> accidentally. I don't see any value of <n> in the code either. Shouldn't <n> be used to limit number of bytes copied over?
26th Apr 2021, 8:37 PM
Ipang
+ 1
@Ipang what do you mean by<n>?
26th Apr 2021, 8:57 PM
Ramisa Fariha
Ramisa Fariha - avatar
+ 1
The task Description said: "function that copies first n bytes ..." That is what I mean by <n>. I thought your code was supposed to read a value of <n> to limit number of bytes to be copied. Anyways, I've found the problem, you need to specify the size of variable <ss> to be at least (length-of-<ss>) + (length-of-<s>) + 1 for string terminator (null).
26th Apr 2021, 9:03 PM
Ipang
+ 1
Ramisa, It depends, If you were allowed to statically specify size of <ss> directly, then just do like that `char ss[30]` But if you're supposed to specify size of <ss> dynamically, then you'd take the `malloc()` and `free()` approach (C way), or `new` and `delete` approach (C++ way). The task didn't clearly specify whether <ss> was to be a static or dynamic char array, so I'm not too sure.
26th Apr 2021, 9:26 PM
Ipang
+ 1
Thank you
26th Apr 2021, 9:27 PM
Ramisa Fariha
Ramisa Fariha - avatar
+ 1
thank you @Martin
27th Apr 2021, 6:58 AM
Ramisa Fariha
Ramisa Fariha - avatar
+ 1
@Martin Thank you so much for elaborating
27th Apr 2021, 7:41 AM
Ramisa Fariha
Ramisa Fariha - avatar