I'm learning pointers in C. To get into details, I'm working on an array program. What I'm trying to achieve is, if the array is of size 0(initially) create a dynamic array using malloc of size 2 and then add the element in the initial position.
Furthermore, when more elements are added and if the total elements == size of the array, I create a new array using malloc with twice the previous size. I create a temporary array, copy elements from the previous array, then add the new element in the end. The problem is when I try to print the elements I get the address of the last element instead of the element.
Here's the full code.
#include<stdio.h>
#include<stdlib.h>
void display(int *arr, int *total_elements)
{
if(*total_elements==0){
printf("No elements present in array\n");
return;
}
else
{
for(int i=0;i< *total_elements;i++){
printf("%d\t",*(arr+i));
}
}
}
void push(int *arr, int *size, int ele, int *total_elements)
{
if(*size==0)
{
*arr = (int*)malloc(2*sizeof(int));
arr[*size] = ele;
*total_elements = *total_elements + 1;
*size = *size + 2;
return;
}
else if(*size>*total_elements)
{
arr[*total_elements] = ele;
*total_elements = *total_elements + 1;
return;
}
else if(*size==*total_elements)
{
int *temp,i;
temp = (int*)malloc((*(size)*2)*sizeof(int));
for(i=0;i < *size;i++)
{
temp[i] = *(arr+i);
}
temp[i]=ele;
arr = temp;
*size = (*size)*2;
*total_elements = *total_elements + 1;
for(int i=0;i< *total_elements;i++){
printf("%d\t",*(arr+i));
}
}
}
void pop()
{
}
void main()
{
int select=0;
int *arr, size=0, total_elements = 0;
while(select!=4)
{
printf("\nSelect a number\n1. push\n2. pop\n3. display\n4. exit\n");
scanf("%d",&select);
switch (select)
{
case 1:
printf("Enter element to push: ");
int ele;
scanf("%d",&ele);
push(arr,&size,ele,&total_elements);
break;
case 3:
display(arr, &total_elements);
break;
case 4: break;
default:
break;
}
}
}
After entering 3 elements(11,22,33). The print output from the push function.
11 22 33
The print output from the display function.
11 22 -1943936495
I'm sure that there is a mistake in the push function while using pointers. Why is this causing?