2

我有两个 char 指针:

char *temp;
char *saveAlias;

我想分配saveAlias存储在的任何内容tempsaveAlias当前为空,而temp从用户输入中保存了一个未知大小的字符串。请注意,我不想saveAlias指出点在哪里temp;我想要 的内容temp并将其分配(指向)它saveAlias

我曾尝试使用strcatstrcpy无济于事。

4

3 回答 3

1

如果要为当前指向的字符串的副本分配内存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-01T17:22:44.950 回答
1

假设您的temp变量指向一个适当nul终止的字符串(如 C 中的字符串应该是),那么您可以使用该strdup()函数制作它的副本并将指向它的指针存储在saveAlias. 该函数会将定的字符串复制到新分配的内存中;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函数有效地组合mallocstrcpy一个函数调用,上面显示的调用等效于:

    char* saveAlias = malloc(strlen(temp) + 1);
    strcpy(saveAlias, temp);
于 2020-12-01T17:22:01.237 回答
0

您基本上可以将 saveAlias 指向 temp;因此,您将拥有:

saveAlias = temp;

正如克里斯所指出的。这将使一个指针指向另一个。更正我的回答。我建议你用 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。

于 2020-12-01T00:04:40.350 回答