×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

Problem statement

Write a C program to create a character pointer (string buffer) and declare memory at run time.

Creating string buffer and declaring memory at run time

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

C program to create string buffer and declare memory at run time

#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.