1

the task in this is to copy the first n characters from (null terminated) string2 (s2) into s1 while using pointers. I know how to copy the strings from one to another, but I am having issues with eliminating the extra values. For example:

s1= 'This is a test'
s2 = 'A test'

after copying, I am left with:

s1 = 'a tests a test'

Here is my code:

char *s1pointer;
const char *s2pointer;
int i;
int number_char_replace;

s1pointer = s1;
s2pointer = s2;
i=0;
number_char_replace = num; 

for(i=0;s1pointer[i] !='\0'||s2pointer[i]!='\0';i++)
{
s1pointer[i]=s2pointer[i];
}
}

This is homework, so please dont feel the need to just give me the answer. A hint for the logic would be greatly appreciated. Thank you.

2
  • I am surprised when OP says its homework and no one jumps out Commented Sep 2, 2013 at 19:19
  • I would say that the real problem here is that the OP didn't know that C strings need to be null-terminated. Now is that his fault, or the professor's? Commented Sep 2, 2013 at 20:52

2 Answers 2

6

You need to somehow indicate the end of the string after the for. Spoiler:

s1pointer[i] = 0;

Sign up to request clarification or add additional context in comments.

3 Comments

Woah. I did not know you could do that!
Thank you for the help, I now have this section of my code outputting what I need.
And on mobile, it says "Click for spoiler" (or something like that)
2

Three problems:

  1. Your target string is not zero terminated when your code finishes. This can cause problems when, e.g., you try to print your string. Also, when you are copying a smaller string on top of a bigger string, it will be impossible to know where the new contents end and the older ones continue.

  2. I understand why you're testing s2pointer[i] !='\0' in your for loop; you want to stop when the source string is exhausted. But why is s1pointer[i] !='\0' there too? Do you need it? Do you know anything about what s1 contains before the copying starts?

  3. You said that you wanted to copy up to n characters. Where is that, in your code?

1 Comment

The s1pointer was an oversight, it didn't hurt my previous outputs in functions so I included it. I forgot including N in the process of trying to figure it all out...I lost the forest in the trees I guess. Let me try to figure out the logic keeping the n in mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.