我正在写C并且必须返回一个char*我正在尝试复制strcpy函数.我有以下代码
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;
}
Run Code Online (Sandbox Code Playgroud)
Q1:如何在没有程序崩溃的情况下将src中的解除引用值分配给目标?
Q2:如果我需要将tmp输入的字符串复制到新字符串中,我该怎么做?我似乎无法tmp作为第二个参数传递
这里
cpyString = strcpy("Sample", cPtr);
^^^^^^^
const
Run Code Online (Sandbox Code Playgroud)
你已经交换了参数.第一个参数是不允许写入的字符串文字("sample").请参阅/sf/answers/314520951/
尝试
cpyString = strcpy(cPtr, "Sample");
Run Code Online (Sandbox Code Playgroud)
我不确定第二行是你想要的,但至少它是合法的.
也许你真的想要:
cpyStringBuffer[100];
cpyString = strcpy(cpyStringBuffer, cPtr);
Run Code Online (Sandbox Code Playgroud)
通常,您的代码main比需要的更复杂.
尝试:
int main()
{
char input[100] = {0};
char dest[100];
printf("Enter word:");
scanf("%99s", input); // notice the 99 to avoid buffer overflow
strcpy(dest, input);
printf("new count is %d\n", strlen(dest));
return 0;
}
Run Code Online (Sandbox Code Playgroud)