I'm writing in C and have to return a char* I am trying to replicate the strcpy function. I have the following code
int main()
{
char tmp[100];
char* cpyString;
const char* cPtr = &tmp[0];
printf("Enter word:");
fflush(stdin);
scanf("%s", &tmp);
cpyString = strcpy("Sample", cPtr);
printf("new count is %d\n", strlen(cpyString));
}
int strlen(char* s)
{
int count = 0;
while(*(s) != 0x00)
{
count++;
s = s+0x01;
}
return count;
}
char* strcpy(char* dest, const char* src)
{
char* retPtr = dest;
int i =0;
int srcLength = strlen(src);
for(i = 0; i< srcLength; i++)
{
*(dest) = *(src); //at this line program breaks
dest = dest + 0x01;
src = src + 0x01;
}
*(dest) = 0x00; //finish with terminating null byte
return retPtr;
}
Q1: How can I assign the dereferenced value at the src to the destination without the program crashing?
Q2: If I need to copy the tmp
string entered into a new string, how would I do that? I can't seem pass tmp
as the second parameter