使用指针的strcpy [英] strcpy using pointers
问题描述
我试着写我自己的使用指针的strcpy,我在运行时出现错误。
I'm trying to write strcpy on my own using pointers and I get an error during runtime.
void str_cpy(char **destination, const char *source) {
// char *s1 = *destination;
while (*source != '\0') {
**destination++ = *source++; //Get an error here
}
**destination = '\0';
}
我调用该函数如下:
I call the function as follows:
char *str = NULL;
str_cpy(&str, "String");
这难道不好吗?
谢谢!
推荐答案
没有,这是不行的。为什么?因为 STR
是 NULL
指针。它指向什么。当您尝试将值写入它,在那里他们将何去何从?它不指向任何分配的内存!
No, it's not okay. Why? Because str
is a NULL
pointer. It's pointing to nothing. When you try to write values into it, where will they go? It's not pointing to any allocated memory!
您必须先分配给 STR
内存。你可以这样做:
You first have to allocate memory for str
. You can do:
char *str = malloc(strlen("String") + 1); // + 1 for the '\0' character at the end of C-style strings
或者,你可以这样做:
Or you can do:
char str[256]; // make str large enough to hold 256 chars. Note that this is not as safe as the above version!
此外,目标
应该是一个指针,而不是一个双指针。好吧,这不是技术上的错误使用双指针,它只是不必要的。
Also, destination
should be a single pointer, not a double pointer. Well, it's not technically wrong to use a double pointer, it's just unnecessary.
或者,您可以分配在 STR_CPY
函数的记忆,像这样:
Optionally, you can allocate the memory in the str_cpy
function, like so:
void str_cpy(char **destination, const char *source) {
*destination = malloc(strlen(source) + 1);
// ... continue as normal
这篇关于使用指针的strcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!