Home > OS >  assign value to a not initialised char* in C
assign value to a not initialised char* in C

Time:10-03

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.

CodePudding user response:

After creating a char* of a certain size, you cannot change it. These strings have a limited length and you can't expand them. But you can create a longer string and then concatenate them.

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

Sadly, the only way to do this relies on dynamic memory management which can be tricky to work with.

CodePudding user response:

if you are worrying about the size of anotherChar, simple you can can convert the code:

char* charName[100];

method(anotherChar) {
    strncpy(charName, anotherChar, sizeOf(anotherChar));
}

into :

char *s = NULL;
void func(char* anotherChar){
    if(s != NULL)
        free(s);

    s = (char *) malloc(strlen(anotherChar) * sizeof(char)   1);
    strcpy(s, anotherChar);
    
}

so every time, we free the old memory allocated in the heap using free(s); and then allocate a new memory in the heap by knowing the information of strlen(anotherChar) which is the length of the string to be assigned till the \0 but excluding \0 and sizeof(char) which is normally 1 byte and we add 1 to reserve a place for the null character at the end of the string.

and at last, we use strcpy(s, anotherChar); to copy all characters till \0 from one string to another.

and this is some text code:

#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 = %s\n", s);

    func("hi");
    printf("s = %s\n", s);

    func("Dummy text");
    printf("s = %s\n", s);


  return 0;
}

and this is the output:

s = hello
s = hi
s = Dummy text
  •  Tags:  
  • c
  • Related