pointer_variable=(typecasting
datatype*)malloc(sizeof(datatype));
This is the syntax for malloc?Please explain this,how it
work with an example?
Answer Posted / vignesh1988i
ya, this is the above syntax for malloc function........
ya i will clearly explain ,
let us take a small block of coding , here my aim is to get 'n' numbers and print the 'n' numbers ......
#include<alloc.h>
void main()
{
int n ,*pointer;
clrscr();
printf("enter the number of elements u r going to enter :");
scanf("%d",&n);
pointer=(int *)malloc(n*sizeof(int));
the above statement states that : , this function is requesting the OPERATING SYSTEM to allocate 'n' amount of memory of a data type integer. and since the return format of the malloc function is an address , so we are type casting as (int*)before malloc , and the returned starting address will be stored in the pointer variable (pointer) ..
this 'pointer' will have the starting address of the allocated memory dynamically...
that's all..
for(int i=0;i<n;i++)
{
scanf("%d",(pointer+i));
}
for(i=0;i<n;i++)
printf("%d\n",*(pointer+i));
getch();
}
thank u
| Is This Answer Correct ? | 6 Yes | 1 No |
Post New Answer View All Answers
Why we use void main in c?
Read the following data in two different files File A: aaaaaaaadddddddd bbbbbbbbeeeeeeee ccccccccffffffff File B: 11111111 22222222 33333333 By using the above files print the following output or write it in the Other file as follows aaaaaaaa11111111dddddddd bbbbbbbb22222222eeeeeeee cccccccc33333333ffffffffffff
Is it better to use a macro or a function?
Explain what is the benefit of using an enum rather than a #define constant?
How can I handle floating-point exceptions gracefully?
Is null valid for pointers to functions?
What is break statement?
Explain the use of function toupper() with and example code?
What is volatile variable in c with example?
How can I write a function that takes a format string and a variable number of arguments?
write a program to rearrange the array such way that all even elements should come first and next come odd
What should malloc() do? Return a null pointer or a pointer to 0 bytes?
What is a function in c?
What are the features of c languages?
Explain what are linked list?