我想为未初始化的字符*赋值。 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)
的信息在堆中分配一个新内存,这是要分配给