I would like to assign a value to a not initialised char*. The char* is global, so a char = "value" just gives me a dangling pointer. I have seen that strncpy could be a viable option. Is it possible that the size of the char* dynamicly changes to the assigned value? Because declaring it with a random high size does not feel right.
Thanks in advance :)
Edit 1:
char* charName[100];
method(anotherChar) {
strncpy(charName, anotherChar, strlen(anotherChar));
}
Is it possible to do this in a cleaner and safer way? It does not feel right to initalize charName with a length of 100, when the length of anotherChar is not known.
Edit 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;
}
}
In this case I get warnings that "API_key" could be '0'. I do not really understand this warning, because I am checking if API_key is NULL and then handling both cases.