Tuesday, March 3, 2009

Pointer in C

A simple example to using pointer in C.

we claim a pointer in main function, and hope to pass it to subroutin to allocate the memory.
How to use it?
Solution 1, return the address back.
=======================
#include
#include

int array_size =10;


int fill_array( float *ptr)
 {
    int i;
printf("Address %d\n", &ptr);
    ptr = (float *) malloc(array_size *sizeof(float));

    for(i=0; i<>
    {
         
      ptr[i] = (float)i;

    }

    
   for(i=0; i
   {
 printf("In function\n");
 
      printf("%d - %f ", &ptr[i],ptr[i]);
   }
   printf("\n");
   printf("ptr = %d\n", &ptr);
   return(ptr);
 }
main()
{
float *ptr = NULL;
int i;
printf("Address %d\n", &ptr);
ptr=fill_array(&ptr);

printf("Out function\n");
printf("Address %d\n", &ptr);
for(i=0; i
{
printf("Out function\n");
printf("%d - %f ", &ptr[i], ptr[i]);
}
}
=======================
The result will be
-------------------------------------
Address 1245052 //ptr in main( )
Address 1244968 //ptr in fill_array( )
In function
4397824 - 0.000000 In function
4397828 - 1.000000 In function
4397832 - 2.000000 In function
4397836 - 3.000000 In function
4397840 - 4.000000 In function
4397844 - 5.000000 In function
4397848 - 6.000000 In function
4397852 - 7.000000 In function
4397856 - 8.000000 In function
4397860 - 9.000000
ptr = 1244968  //ptr in fill_array( )
Out function
Address 1245052
Out function
4397824 - 0.000000 Out function
4397828 - 1.000000 Out function
4397832 - 2.000000 Out function
4397836 - 3.000000 Out function
4397840 - 4.000000 Out function
4397844 - 5.000000 Out function
4397848 - 6.000000 Out function
4397852 - 7.000000 Out function
4397856 - 8.000000 Out function
4397860 - 9.000000 Press any key to continue
-------------------------------------

Solution 2 , call by address.
=======================
#include
#include

void function(float ** ptrf)
{

int i;
printf("address of *ptrf = %d\n", &*ptrf);
*ptrf = (float *) malloc(5*sizeof(float*));
printf("address of *ptrf = %d\n", &*ptrf);
for(i=0; i<5;>
{
(*ptrf)[i] =i;
}
}

int main()
{
float *ptr=NULL;

int i;
printf("address of *ptr = %d\n", &ptr);
function(&ptr);

for(i=0; i<5;>
{
printf("%f ", ptr[i]);
}
printf("\nAddress ponited to by the ptr out function \nptr=%d, &ptr=%d\n", ptr, &ptr);
}
=======================
The result will be
---------------------------------
address of *ptr = 1245052
address of *ptrf = 1245052
address of *ptrf = 1245052
0.000000 1.000000 2.000000 3.000000 4.000000
Address ponited to by the ptr out function
ptr=4397856, &ptr=1245052
Press any key to continue
---------------------------------

No comments:

Clicky

Clicky Web Analytics