我有两个字符指针:
char *temp;
char *saveAlias;我希望将存储在temp中的内容赋给saveAlias;saveAlias当前为空,而temp有一个从用户输入中保存的未知大小的字符串。请注意,我不希望saveAlias指向temp所指向的位置;我希望将temp的内容分配(指向)给saveAlias。
我尝试过使用strcat和strcpy,但都无济于事。
发布于 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
复制相似问题