pointer_variable=(typecasting
datatype*)malloc(sizeof(datatype));
This is the syntax for malloc?Please explain this,how it
work with an example?
Answers were Sorted based on User's Feedback
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 |
Answer / pramod
I'll add few more lines to answer above just to make it a
bit more understandable.
Malloc allocates consequetive blocks of memory of requested
size.Then it returns the starting address of this block ,
the address returned is of type void , since it is a void
pointer so we need to typecast it to one that we requested
so typecasting is done( This headache has been removed in
C++ by using new as new automatically does this typecasting)
| Is This Answer Correct ? | 2 Yes | 0 No |
What is the right type to use for boolean values in c?
Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
12. Look at the Code: main() { int a[]={1,2,3},i; for(i=0;i<3;i++) { printf("%d",*a); a++; } } Which Statement is/are True w.r.t the above code? I.Executes Successfully & Prints the contents of the array II.Gives the Error:Lvalue Required III.The address of the array should not be changed IV.None of the Above. A)Only I B)Only II C)II & III D)IV
What is meant by initialization and how we initialize a variable?
What are local static variables? How can you use them?
Please write the area of a RIGHT ANGLED TRIANGLE.
What will be the outcome of the following conditional statement if the value of variable s is 10?
if a is an integer variable, a=5/2; will return a value a) 2.5 b) 3 c) 2 d) 0
how can i get the output 54321 4321 321 21 1 in c programming........???? pls help......
can we write a program in c for printf and scanf without using header file stdio.h
program that accepts amount in figures and print that in words
2 Answers Infosys, Lovely Professional University, Wipro,
how can be easily placed in TCS.