将值赋值给 C 中未初始化的字符*

  • 本文关键字:初始化 字符 赋值 c
  • 更新时间 :
  • 英文 :


我想为未初始化的字符*赋值。 char* 是全局的,所以 char = "值"只是给了我一个悬空的指针。 我已经看到strncpy可能是一个可行的选择。字符* 的大小是否有可能动态更改为分配的值? 因为用随机的高尺寸声明它感觉不对。

提前致谢:)

编辑 1:

char* charName[100];
method(anotherChar) {
strncpy(charName, anotherChar, strlen(anotherChar));
}

是否有可能以更清洁、更安全的方式做到这一点?当另一个字符的长度未知时,将长度为 100 的 charName 启动是不对的。

编辑 2:

char API_key;
void func(char* message) {
if (waiting_for_user_input && message != NULL) {
if (API_key == NULL) {
API_key = (char*)malloc(strlen(message));
strcpy(API_key, message);
}
else {
API_key = (char*)realloc(API_key, strlen(message));
strcpy(API_key, message);
}
waiting_for_user_input = false;
}

}

在这种情况下,我收到警告说"API_key"可能是"0"。我不太理解这个警告,因为我正在检查API_key是否为 NULL,然后处理这两种情况。

如果你担心anotherChar的大小,简单就可以转换代码:

char* charName[100];
method(anotherChar) {
strncpy(charName, anotherChar, sizeOf(anotherChar));
}

到:

char *s = NULL;
void func(char* anotherChar){
if(s != NULL)
free(s);
s = (char *) malloc(strlen(anotherChar) * sizeof(char) + 1);
strcpy(s, anotherChar);

}

因此,每次,我们都使用free(s);释放堆中分配的旧内存,然后通过知道strlen(anotherChar)的信息在堆中分配一个新内存,这是要分配给的字符串的长度,但不包括sizeof(char)通常为 1字节,我们添加1为字符串末尾的空字符保留一个位置。

最后,我们使用strcpy(s, anotherChar);将所有字符复制到从一个字符串复制到另一个字符串。

这是一些文本代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *s = NULL;
void func(char* anotherChar){
if(s != NULL)
free(s);
s = (char *) malloc(strlen(anotherChar) * sizeof(char) + 1);
strcpy(s, anotherChar);
}
int main(void) {
func("hello");
printf("s = %sn", s);
func("hi");
printf("s = %sn", s);
func("Dummy text");
printf("s = %sn", s);

return 0;
}

这是输出:

s = hello
s = hi
s = Dummy text

创建特定大小的 char* 数组后,无法更改它。这些字符串的长度有限,您无法扩展它们。但是,您可以创建一个更长的字符串,然后将它们连接起来。

char* new_string = (char*) malloc((strlen(a) + strlen(b) + 1) * sizeof(char));
strcpy(new_string, a);
strcat(new_string, b);
printf("%s", new_string);

可悲的是,执行此操作的唯一方法依赖于动态内存管理或VLA,这可能很难使用。

最新更新