initialize char pointer c code example

Example: initialize char pointer c

//you should probably use dynamic memory allocation
//this string is uninitialized and will cause errors
char *str1; 
//this string is initialized, but you would have to come up with text
//I would highly discourage using this method
char *str2 = "DummyTextThatFillsOutThisSpace";
//this is dynamic memory allocation
//You have to have a max size for the string
//sizeof(dataType) returns the memory size of the data type
//another reminder: ALWAYS free dynamically allocated memory
int MaxSize = 10;
char *str3 = malloc(MaxSize * sizeof(char));
//code to use string
//ALWAYS free dynamically allocated memory
free(str3);

Tags:

C Example