Home > Enterprise >  C Pointers and Memory Allocation
C Pointers and Memory Allocation

Time:10-11

I am taking a C class in school and was give a few lines of code with errors and I'm having trouble finding all 4 errors. The code is supposed to print the number "302" I'm not good with pointers. Here is the code

int main () {
int* ptr;
int* temp;
int x;
ptr = int;
*ptr = 3;
cout << ptr << endl;
x=0;
temp = x;
cout<<*temp<< endl;
ptr = int;
*ptr = 2;
cout<<*ptr-*temp <<endl;
return 0;
}

The two errors i have found so far are

  1. cout and endl need to have ::std in front of them
  2. temp = x needs to be a pointer, *temp = x

CodePudding user response:

Include <iostream> to sort out cout, endl errors. Typically C compiler needs to know from where these functions are coming.

#include <iostream>

use std::cout and std::endl instead of just cout and endl.

new operator was missed in ptr and temp pointers

ptr = new int;
temp = new int;

Note, as you are dynamically allocating memory for ptr and temp, ensure it is removed via delete ptr, delete temp after its usage.

CodePudding user response:

For less line of code i prefer using namespace std globally, this will resolve the problem of using std::cout everytime

using namespace std;

other than that you will have to allocate memory to the pointer after declaring it which can be done by using the new operator(don't forget to deallocate the memory after ur work is done using the delete operator), so instead of ptr = int; use

ptr = new int;

also using temp = x; is wrong as u are assigning the address of pointer temp to a varible value, using temp = &x; should be the right approach

CodePudding user response:

Other answers already pointed out the problems, their explanation and a possible solution, except for problem in this:

  1. temp = x needs to be a pointer, *temp = x

No, you are wrong here. Pointer temp is uninitialised and dereferencing an uninitialised pointer (*temp) will lead to Undefined Behaviour. Two ways you can solve it:

First, allocate memory to temp

temp = new int;

and then you can do this

*temp = x;

In this, the memory allocated to temp will have an independent copy of value of x. Make any changes to value of x does not reflect in the content of memory pointed by temp pointer and vice versa. Make sure to deallocate the storage allocated to temp, once you done with it because the memory it is pointing to is allocated dynamically.

Second, assign address of x to temp pointer

temp = &x;

temp pointer is pointing to x. Make any changes to the value of x and *temp will give the current value of x and vice versa. No need to deallocate the temp because the memory it is pointing to is not allocated dynamically.

  • Related