I want to make a dynamic array. but when I view the array, I think there's something wrong with the index part. Please help. Thanks!

here's my code:

#include<stdio.h>


main(){

	int* a;
	int number;
	int choice;
	int index = 0;
	int head;
	
	
	while(choice!=4){
	
		printf("\tMENU\t\n");
		printf("[1] add number to array\n");
		printf("[2] view array\n");
		printf("[3] search using linear search\n");
		printf("[4] quit program\n");
		scanf("%d", &choice);
		
		switch(choice){
			case 1: head = add(&index, a);
					break;
			
			case 2:head = view(&index,a);
					break;
					
			//case 3:linsearch(&index,array[5]);
					//break;
					
			case 4: return;
					break;
					
			default: printf("invalid input!!!\n");
			
		}
}
}

 int add(int* index, int* a){
	
	int number;
	int i;
	
		printf("enter number you want to enter in the array.\n");
		scanf("%d", &number);
		
		*a = (int) malloc (5*sizeof(int));
		
		for(i = 0; i <= *index; i ++){
			a[i] = number;
		}
		
		return *index;
}

 view(int* index, int* a){

	int i; 
	printf("\n");
	
		for(i = 0; i <= *index; i++){
			printf("index: %d, %d ", *index, a[i]);
		}
		printf("\n\n");
		
		return a[5];
}

Recommended Answers

All 2 Replies

Function add() -- second parameter must also be passed by reference. You are just passing the pointer by value, which does nothing in main()'s copy of the pointer. Note the second parameter should have two stars, not one.

int add(int* index, int **a)
{

}

lint 49: The typecast is wrong so you might as well just remove it because malloc() does not need to be typecast in C programs.

thanks a lot!
my program finally worked.

i changed the ad part to:

if(*index < 5){
			printf("enter number you want to enter in the array.\n");
			scanf("%d", &a[*index]);
			(*index)++;
			
		}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.