378 views
0 votes
0 votes

For creating a N integer array

is there any mistake in this line?

int numArray[N]=(int *) malloc(N);

 

1 Answer

0 votes
0 votes

malloc(n)-Reserves a block of memory of specified(n) number of bytes.

After the definition we're well equipped to answer that question.Your requirement is to  create an array which stores n integers(or equivalently, n integer sized blocks) and not a memory block of n bytes,i hope you're getting the difference. Now, to achieve this,intuitively if we multiply size of an integer with number of bytes(n*sizeof(int)),we should be getting required number of memory blocks(n blocks each of 4 or 2 bytes(size of integer might vary with different compilers :) ).Equivalent syntax is as below:

int *a=(int*)malloc(sizeof(int)*n);

 

Related questions

1 votes
1 votes
1 answer
1
jugnu1337 asked May 10, 2022
260 views
SOURCE NAME::: UNDERSTANDING POINTER IN C (BOOK) BY YASHWANT KANETKARmy answer is C am i right?
1 votes
1 votes
0 answers
2
aakash pandey asked Apr 30, 2022
281 views
We use character array to declare string in C. So, if I declare an array likecharacter ch[ ] = {‘a’,’k’,’a’,’/o’};and try printing ch[3] like :printf(“%...
0 votes
0 votes
0 answers
3
Anirudh Kaushal asked Apr 6, 2022
191 views
#include<stdio.h struct marks { int p:3; int c:3; int m:2; }; void main() { struct marks s = {2, -6, 5}; printf("%d %d %d", s.p, s.c, s.m); }What does p:3 means here ?
0 votes
0 votes
0 answers
4