In this array insertion code, the value of usedsize
does not get updated when I increment it inside the void insert
function. I want to know why that keeps happening and why the value of arr[i]
gets updated when this doesn't?
#include <stdio.h>
#include <stdlib.h>
void insert(int arr[], int element, int index, int usedsize){
for(int i=usedsize;i>=index;i--){
arr[i+1]=arr[i];
}
arr[index]=element;
usedsize++;
}
void traverse(int arr[], int size){
for(int i=0;i<size;i++){
printf("%d",arr[i]);
printf("\t");
}
}
int main()
{
int narr[25]={5,7,12,34,45};
int index = 3;
int usize = 5;
int element = 21;
insert(narr,element,index,usize);
traverse(narr,usize);
return 0;
}
Like the commenters noted, the variable usedsize
in the insert
function is a copy.
why does the value of arr[i] get updated?
In C, the array name indicates the address of first element and arrays are always passed as pointers, even if you use the square bracket notation 0.
#include <stdio.h>
#include <stdlib.h>
void insert(int arr[], int element, int index, int *usedsize) {
printf("Address arr[%d] is %p\n", 0, &arr[0]);
printf("Address usedsize is %p\n", usedsize);
for(int i=*usedsize; i>=index; i--) {
arr[i+1]=arr[i];
}
arr[index]=element;
(*usedsize)++;
}
int main()
{
int narr[25]= {5,7,12,34,45};
int index = 3;
int usize = 5;
int element = 21;
printf("Address arr[%d] is %p\n", 0, &narr[0]);
printf("Address usize is %p\n", &usize);
insert(narr,element,index,&usize);
traverse(narr,usize);
return 0;
}
Original code:
- Address arr[0] is 0x7ffdf2f8b510
- Address usize is 0x7ffdf2f8b504
- Address arr[0] is 0x7ffdf2f8b510
- Address usedsize is 0x7ffdf2f8b4cc
Now:
- Address arr[0] is 0x7fff0c03d740
- Address usize is 0x7fff0c03d734
- Address arr[0] is 0x7fff0c03d740
- Address usedsize is 0x7fff0c03d734