我有两个字符指针:
char *temp;
char *saveAlias;我希望将存储在temp中的内容赋给saveAlias;saveAlias当前为空,而temp有一个从用户输入中保存的未知大小的字符串。请注意,我不希望saveAlias指向temp所指向的位置;我希望将temp的内容分配(指向)给saveAlias。
我尝试过使用strcat和strcpy,但都无济于事。
发布于 2020-12-02 01:22:01
假设您的temp变量指向一个适合nul-terminated的字符串(正如C中的字符串应该是这样),那么您可以只使用strdup() function来复制它,并在saveAlias中存储一个指向它的指针。这个函数将dup给定字符串复制到新分配的内存中;当不再需要时,应该使用free函数释放该内存:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char* temp = "source string";
char* saveAlias = strdup(temp);
printf("Temp is <%s> (at %p).\n", temp, (void*)temp);
printf("Alias is <%s> (at %p).\n", saveAlias, (void*)saveAlias);
free(saveAlias);
return 0;
}strdup函数将malloc和strcpy有效地组合到一个函数调用中,上面显示的调用等同于:
char* saveAlias = malloc(strlen(temp) + 1);
strcpy(saveAlias, temp);发布于 2020-12-02 01:22:45
如果要为temp当前指向的字符串的副本分配内存,请使用strdup()
#include <stdio.h>
#include <string.h>
int main() {
char buf[128];
char *temp;
char *saveAlias = NULL;
if ((temp = fgets(buf, sizeof buf, stdin)) != NULL) {
saveAlias = strdup(temp);
if (saveAlias == NULL) {
fprintf(stderr, "allocation failed\n");
} else {
printf("saveAlias: %s\n", saveAlias);
}
}
free(saveAlias);
return 0;
}发布于 2020-12-01 08:04:40
基本上,您可以将saveAlias指向temp;因此,您将拥有:
saveAlias = temp;
正如Chris所指出的。这将使一个指针指向另一个指针。更正我的答案。我建议你用malloc定义saveAlias的大小,然后使用memcpy函数。您将拥有:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char *temp = "your_char";
//with malloc you make sure saveAlias will have the same size as temp
//and then we add one for the NULL terminator
char *saveAlias = (char*) malloc(strlen(temp) + 1);
//then just
strcpy(saveAlias, temp);
printf("%s\n", temp);
printf("%s", saveAlias);
return 0;
}也感谢chqrlie的解释。我搞错了memcpy。
https://stackoverflow.com/questions/65082782
复制相似问题