I am trying to write the code for the “String Copier” project (link to the project
)
that comes with the C lesson on pointers.
I don’t understand what’s wrong with my code.
It outputs a bunch of error messages which I don’t understand. Could you help?
#include<stdio.h>
#include<string.h>
void copy(char* dst, char* src){
while(*src != '\0'){
strcpy(*dst,*src);
src++;
dst++;
}
*dst= '\0';
}
int main(){
char srcString[] = "We promptly judged antique ivory buckles for the next prize!";
int len= strlen(srcString) + 1;
char dstString[len]{
strcpy(*dstString,*srcString);
printf("%s",dstString);
}
}
We have similar code. I wish I am knowledged enough to explain each line in detail.
I tried this and it worked:
#include<stdio.h>
#include<string.h>
void copy(char* dst, char* src){
while(*src != '\0') {
strcpy(dst, src);
src++;
dst++;
*dst += '\0';
}
}
int main(){
char srcString[] = "We promptly judged antique ivory buckles for the next prize!";
char dstString[strlen(srcString)+1] = "";
copy(dstString, srcString);
printf("%s", dstString);
}
Mine has no error but outputs nothing, not even, no result at all 
It goes like this:
#include<stdio.h>
#include<string.h>
void copy(char* dst, char* src){
while (*src != ‘\0’){
char *strcpy (char *dst, char const *src);
dst++;
src++;
}
*dst = ‘\0’;
}
int main(){
char srcString = “We promptly judged antique ivory buckles for the next prize!”;
char dstString[strlen(srcString) + 1];
copy(dstString, srcString);
printf(“This is my destination string: %s”, dstString);
return 0;
}
Hey!
So I’ve worked on it for some time now and found it super confusing. I found this video quite helpful, I also brushed up some concepts about pointers and their application on YouTube:
My code now looks like this, and it works just fine:
#include<stdio.h>
#include<string.h>
void copy(char* dst, char* src){
while (*src != ‘\0’)
{
*dst = *src;
src++;
dst++;
}
*dst = ‘\0’; // this is necessary because after the loop finishes, *dst will stop one short of ‘\0’ as the loop will terminate just before reaching the terminating character, making prinf unable to print the string
}
int main(){
char srcString = “We promptly judged antique ivory buckles for the next prize!”;
char dstString[strlen(srcString) + 1]; // this is used to account for the terminating character (‘\0’)
copy(dstString, srcString);
printf(“%s”, dstString);
}