By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,183 Members | 1,179 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,183 IT Pros & Developers. It's quick & easy.

new replacing malloc

P: 9
Hi!
Can someone tell me the correct answer for these ...

Replace the following code using new operator-
(Assume int is 2 bytes)
#define MAXROW 3
#define MAXCOL 4

1.)
void main()
{
int (*p)[MAXCOL];
p=(int(*) [MAXCOL]) malloc(MAXROW*sizeof(*p));
}


2.)
void main()
{
int (*p)[MAXROW][MAXCOL];
p=(int(*) [MAXROW][MAXCOL]) malloc(sizeof(*p));
}


3.)
void main()
{
int **p,i;
p=new int *[MAXROW];
for(i=0;i<MAXROW;i++)
p[i]=new int[MAXCOL];
}

4.)
void main()
{
int **p,i;
p=(int**)malloc(MAXROW*sizeof(int *));
p[0]=(int *)malloc(MAXROW*MAXCOL*sizeof(int));
for(i=0;i<MAXROW;i++)
p[i]=p[0]+i*MAXCOL;
}
Oct 7 '06 #1
Share this Question
Share on Google+
5 Replies


100+
P: 293
D_C
It is unlikely until you tell us what the question is. Is it "how to rewrite the following code using new rather than malloc"?
Oct 8 '06 #2

P: 9
It is unlikely until you tell us what the question is. Is it "how to rewrite the following code using new rather than malloc"?
Yes! That's exactly what the question is !
Oct 9 '06 #3

Banfa
Expert Mod 5K+
P: 8,916
I think you should probably attempt this yourself first (it looks like course/home work to me).

Bear in mind that these are equivilent

Expand|Select|Wrap|Line Numbers
  1. int *pi = malloc(5 * sizeof(int));
  2.  
  3. int *pi = malloc(5 * sizeof *pi);
  4.  
  5. int *pi = new int[5];
  6.  
Oct 9 '06 #4

P: 9
I think you should probably attempt this yourself first (it looks like course/home work to me).

Bear in mind that these are equivilent

Expand|Select|Wrap|Line Numbers
  1. int *pi = malloc(5 * sizeof(int));
  2.  
  3. int *pi = malloc(5 * sizeof *pi);
  4.  
  5. int *pi = new int[5];
  6.  
==============

Hi Ben,

No, its not a course/home work !
I n fact the question is from a book and they have given the answers too . but I am not sure that the answers are right. i have an interview 2morrow n it will be really helpful if u check these-

(these r the answers from the book itself)

1. p=new int [MAXROW][sizeof(*p)/sizeof(int)];

2. p=new int[1]MAXROW][MAXCOL];

3. this one i think is correct
p=new int*[MAXROW];
for(----)
p[i]=new int [MAXCOL];


4. this too i think is correct
p=new int*[MAXROW];
p[0]=new int [MAXROW * MAXCOL];
Oct 10 '06 #5

Banfa
Expert Mod 5K+
P: 8,916
This is probably late (sorry I shall blame the cold that has wiped out the past couple of days) but I think that all there solutions are syntatically correct. Not that I think they are necessarily a good idea.
Oct 10 '06 #6

Post your reply

Sign in to post your reply or Sign up for a free account.