2 Replies - 347 Views - Last Post: 03 August 2014 - 05:52 AM Rate Topic: -----

#1 jmar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 02-August 14

Assigning a pointer (int *) located in Main with another function

Posted 02 August 2014 - 11:11 PM

I have the following:

int Allocate(int, int *);

main()
{
     int *Pointer;
     int  Elements = 25;

     // this works just fine - as expected.

    Pointer = (int *) malloc(Elements, sizeof(int));

    // This DOES NOT - The value of Pointer never changes.....
    // It is like Pointer has been declared as const int *Pointer;
    // The function Allocate WILL assign a malloc value to the Pointer
    // but that value goes away when the function returns to main.  I don't
    // want to return a pointer because I need to return an int in the real code.

    Allocate(Elements, Pointer);

    // Since I'm passing Allocate a pointer (Pointer), why doesnt Pointer get
    // assigned correctly in the function Allocate?

//  Pointer = the same value before Allocate, even though the malloc in Allocate
//            correctly assigned an allocated pointer to Ptr.
}
int Allocate(int Count, int *Ptr)
{
       Ptr = (int *) malloc(Count * sizeof(int));
}

This post has been edited by Salem_c: 03 August 2014 - 07:15 AM
Reason for edit:: added code tags - learn to use them yourself


Is This A Good Question/Topic? 0
  • +

Replies To: Assigning a pointer (int *) located in Main with another function

#2 Peter O  Icon User is offline

  • D.I.C Head

Reputation: 83
  • View blog
  • Posts: 199
  • Joined: 19-October 13

Re: Assigning a pointer (int *) located in Main with another function

Posted 03 August 2014 - 12:50 AM

Pointers are passed "by value" like any other type which means that the function will receive a copy of argument that was passed to the function. Modifying the copy will not affect the original pointer.

In C++ you could solve this by passing the argument as a reference but in C you will have to pass a pointer to the pointer to allow the function to modify the pointer.

int Allocate(int, int **);

main()
{
	int *Pointer;
	int Elements = 25;
	Allocate(Elements, &Pointer);

}

int Allocate(int Count, int **Ptr)
{
	*Ptr = (int *) malloc(Count * sizeof(int));
}

Was This Post Helpful? 1
  • +
  • -

#3 jmar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 02-August 14

Re: Assigning a pointer (int *) located in Main with another function

Posted 03 August 2014 - 05:52 AM

Thank you SOOOO much. I have not coded in C for a bit, and I could not figure out how to pass the function the address of the pointer. It's been driving me crazy. I am allergic to C++. Thank you again for your assistnace in this matter.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1