Pointer assignment vs strcpy in C

#include <stdio.h> #include <stdlib.h> #include <string.h> char* str; int num; void create() { num = 100; str = malloc(sizeof(char) * num); } void process() { char example[100] = "This is a test"; // BAD, pointer to example gets copied, example will be deallocated // str = example; // GOOD, example's contents get copied strcpy(str, example); printf("%s\n", str); } int main(int argc, char* argv[]) { create(); process(); printf("String from process(): %s\n", str); return 0; }

Courses with this lesson