logo

String literals and string initializations

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { // Const string, will break // char *str = "Hello!"; // String on the stack, will work // char str[] = "Hello!"; // Dynamically allocated string on the heap, will work char *str = malloc(50, sizeof(char)); strcpy(str, "Hello!"); printf("%s\n", str); str[0] = 'h'; printf("%s\n", str); // Only needed for dynamically allocated string free(str); return 0; }

Courses with this lesson