Creating string buffer (character pointer), allocating memory at run time in C

Here, we are going to learn how to create a character pointer (string buffer), how to declare memory at run time in C language?
Submitted by IncludeHelp, on September 26, 2018

By using pointers, and dynamic memory allocation – we have to declare a character pointer, allocate memory at run time in C language.

Example:

#include <stdio.h>
#include <string.h>

#define MAX 100

int main()
{
    //declaring character pointer
    char *buffer;
    
    //allocating memory at run time
    buffer = (char*)malloc(MAX*sizeof(char));
    if(buffer==NULL)
    {
        printf("Error in allocating memory!!!\n");
        return -1;
    }
    
    //assign any string
    strcpy(buffer,"Hello, World");
    //printing
    printf("buffer: %s", buffer);
    
    //freeing memory
    free(buffer);
    
    return 0;
}

Output

buffer: Hello, World

C String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.