Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Code1:

int *pint = nullptr;
pint = new int;
if (pint == nullptr)
*pint = 100;
else
cout << "Memory allocation error\n";

Code 2:
void doSomething(int * const ptr)
{
int localArray[] = { 1, 2, 3 };
ptr = localArray;
}

What I have tried:

code 1:
int *pint = nullptr;
pint = new int;
int x;
if (pint == &x)
*pint = 100;
else
cout << "Memory allocation error\n";


code 2:
void doSomething(int * ptr)
{
int localArray[] = { 1, 2, 3 };
ptr = localArray;
}
Posted
Updated 20-Mar-23 7:43am
Comments
CHill60 20-Mar-23 11:05am    
What is your question? Does this code compile - if not then what is the error message?
Does it run but it is doing something unexpected? Is so, then what is it doing?

Check your test comparisons. You have
C++
if ( pint == nullptr )
   *pint = 100;
This is exactly backwards. If pint is NULL after the new operator, then the memory allocation has failed. In all likelyhood, attempting to assign a value to the pointer (value 0) will cause the program to crash.
 
Share this answer
 
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

Start by reading the code and working out what it does and why that might be a problem.
Hint: what will happen if you execute this line in your first assignment?
C++
*pint = 100;
 
Share this answer
 
You seem to be posting your homework assignments, and asking other people to do your work for you.

The point of the assignment is to think about what you know about each statement in the code. This points out deficiencies in your knowledge that you need to fix. Asking other people to do the thinking for you defeats the purpose of the assignment and will only lead to you having far bigger problems later in the class and other classes.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900