Q:

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

belongs to collection: C String Programs

0

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

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
memcpy() function in C with Example... >>
<< C program to read time in string format and extrac...