wap to store a character string in block of memory space created by malloc and then modify the same to store a large string
Answers
Answer:
ik
r
c
d
d
d
d
d
d
d
dd
d
d
d
d
d
d
d
d
d
d
d
d
d
2
r
r
d
d
Explanation:
what is this
Answer:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int n, i;
printf("Enter the size or the number of characters that you want to enter inside the string.\n");
scanf("%d",&n);
// malloc is used for assigning the memory to a block
char *p = (char*)malloc((n+1)*sizeof(char));
if(p==NULL)
{
printf("Memory allocation fails..");
exit(0);
}
puts("Enter string");
for(i=0;i<(n+1);i++)
scanf("%c",p+i);
*(p+i)= '\0';
printf("String entered %s",p);
fflush(stdin);
printf("\nEnter new size\n");
scanf(" %d",&n);
p = realloc(p,(n+1)*sizeof(char)); // realloc
puts("Enter new string");
scanf("%d", &n);
for(i=0;i<(n+1);i++)
scanf("%c",p+i);
*(p+i)= '\0';
printf("New string \n%s",p);
free(p);
return 0;
}
Explanation:
To dynamically allocate one sizable block of memory with the specified size, use the "malloc" or "memory allocation" technique in the C programming language. It returns a void-type pointer that may be cast into any other kind of pointer. Because memory is not initialized at execution time, each block has been initially initialized with the default trash value.
To dynamically de-allocate the memory in C, use the "free" technique. The memory allocated with the help of the methods malloc() and calloc() is not automatically released. The free() function is thus utilized anytime dynamic memory allocation occurs. By releasing memory, it aids in reducing memory waste.
To know more about the malloc, click on the link below:
https://brainly.in/question/54679955
To know more about memory allocation in C, click on the link below:
https://brainly.in/question/43364003
#SPJ2