Академический Документы
Профессиональный Документы
Культура Документы
Anurag Rana
What is a pointer?
A pointer is a variable whose value is the address of
another variable.
Solution -
Allocate memory dynamically.
int main()
{
int n1 = 5;
int n2 = 10;
swap(&n1, &n2);
return 0;
}
Returning pointer from Function
- Declare the return type as pointer.
- Allocate memory inside function.
- return the pointer to allocated block of memory.
- function caller is responsible of deallocating the memory.
int* allocateArray(int size, int value)
{ int* vector = allocateArray(5,45);
int* arr = (int*)malloc(size *sizeof(int)); for(int i=0; i<5; i++)
for(int i=0; i<size; i++) {
{ printf("%d\n", vector[i]);
arr[i] = value; }
}
return arr;
}
Returning pointer from Function
To understand better, always heap
create a memory diagram.
Returning pointer from Function
Make sure you do not return address of local variable, i.e.
memory is allocated from heap only and not from stack.
Example -
int* allocateArray(int size, int value)
{ This arr is created in stack
int arr[size];
for(int i=0; i<size; i++)
frame of allocateArray
{ method and hence
arr[i] = value;
} address returned doesnt
return arr;
}
remain valid.
double pointer again.
void allocateArray(int **arr, int size, int value)
void allocateArray(int *arr, int size, int value)
{
{
int i;
int i;
*arr = (int*)malloc(size * sizeof(int));
arr = (int*)malloc(size * sizeof(int));
if(*arr != NULL)
if(arr != NULL)
{
{
for(i=0; i<size; i++)
for(i=0; i<size; i++)
{
{
*(*arr+i) = value;
*(arr+i) = value;
}
}
}
}
}
}
int main()
int main()
{
{
int *vector = NULL;
int *vector = NULL;
allocateArray(&vector,5,45);
allocateArray(&vector,5,45);
printf("%p\n",vector);
printf("%p\n",vector);
return 0;
return 0;
}
}
//Explain - Diagram of stack frames
Function Pointer - Introduction
void * fun (); void (* fun) ();
for(i=0;i<count;i++){
*(ptr+i) = i;
}
Pointers and Arrays : 3 ways to think
Example ?
Passing 1D-array to function
int arr[3] = {1,2,3}; Receiving and using 1D array:
func(arr); void func(int a[ ]) { a[i]; }
arr[i] = (int*)malloc(sizeof(int));
*arr[i] = i;
is equivalent to
*(arr+i) = (int*)malloc(sizeof(int));
*(*(arr+i)) = i;
Dynamically Allocating Arrays
1D:
int *vector = (int *) malloc(sizeof(int)*count);
2D:
int **matrix = (int **)malloc(rows * sizeof(int*));
for(i=0;i<rows;i++){
seperate malloc calls;
matrix[i] = (int *) malloc (columns* sizeof(int)); discontinous allocation
of memory
}
Dynamically Allocating Arrays
Continous allocation: