Memory in C must be allocated. There's two basic types: stack or automatic memory, and heap or malloc
memory. Stack is called "automatic" because it will be automatically freed for you once you leave the block. heap
requires that you manually allocate and free the memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// A character array.
char char_ptr1[] = "this is a string";
// Allocate space for the string and its null byte.
// sizeof(char_ptr1) only works to get the length on
// char[]. On a *char it will return the size of the
// pointer, not the length of the string.
char* char_ptr2 = malloc(sizeof(char_ptr1));
// We need copies of the pointers to iterate, else
// we'll lose their original positions.
char *src = char_ptr1; // Arrays are read-only. The array will become a pointer.
char *dest = char_ptr2;
while(*src != '\0')
*dest++ = *src++;
// Don't forget the terminating null byte.
*dest = '\0';
printf("%s\n", char_ptr2);
// All memory will be freed when the program exits, but it's good
// practice to match every malloc with a free.
free(char_ptr2);
}
The standard function to do this is strcpy
. Be careful to be sure you've allocated sufficient memory, strcpy
will not check for you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char char_ptr1[] = "this is a string";
char* char_ptr2 = malloc(sizeof(char_ptr1));
strcpy(char_ptr2, char_ptr1);
printf("%s\n", char_ptr2);
free(char_ptr2);
}
And the POSIX function strdup
will handle both the allocation and copying for you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char char_ptr1[] = "this is a string";
char* char_ptr2 = strdup(char_ptr1);
printf("%s\n", char_ptr2);
free(char_ptr2);
}