I'm attempting to create an array using an Abstract Data Type (ADT) in C, but I seem to be facing a logical error. While there are no compilation issues, the output is not as expected. I've provided my code below:
#include<stdio.h>
#include<stdlib.h>
struct myArray{
int total_size;
int used_size;
int *ptr;
};
void createArray(struct myArray*a, int tsize, int usize){
/*(*a).total_size = tsize;
(*a).used_size = usize;
(*a).ptr = (int*)malloc(tsize*sizeof(int));*/
a->total_size = tsize;
a->used_size = usize;
a->ptr = (int*)malloc(tsize*sizeof(int));
}
void setVal(struct myArray*a){
int n;
int i;
for(i=0; i<a->used_size; i++){
printf("enter element %d - \n",i);
scanf("%d",&n);
n = a->ptr[i];
}
}
void show(struct myArray*a){
int i;
for(i=0; i<a->used_size; i++){
printf("%d",(a->ptr[i]));
}
}
int main(){
struct myArray marks;
createArray(&marks, 10, 2);
printf("we are running setval now\n");
show(&marks);
printf("we are running show now\n");
setVal(&marks);
return 0;
}
The output I'm currently getting is:
we are running setval now
00we are running show now
enter element 0 -
However, the expected output should be:
We are running setVal now
Enter element 0 - 1
Enter element 1 - 2
We are running show now
1
2
Any help in identifying the logical error would be greatly appreciated. Thank you!
There are a few peculiar issues in the OP code:
setVal(), the linen = a->ptr[i];should bea->ptr[i] = n;in order to write the value into the array.show(), the callprintfshould add a newline:printf("%d\n",(a->ptr[i]));.main(), the lineshow(&marks);andsetVal(&marks);should be switched (first set, then show).With these updates, the result is as expected.
On a more conceptual level, to make an abstract data type, the definition of
myArrayshould not be visible outside the data type implementation. See e.g. this question/answers for an old, but thorough discussion.