Issues with Creating an Array using ADT in C

72 Views Asked by At

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!

1

There are 1 best solutions below

0
nielsen On

There are a few peculiar issues in the OP code:

  • In setVal(), the line n = a->ptr[i]; should be a->ptr[i] = n; in order to write the value into the array.
  • In show(), the call printf should add a newline: printf("%d\n",(a->ptr[i])); .
  • In main(), the line show(&marks); and setVal(&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 myArray should not be visible outside the data type implementation. See e.g. this question/answers for an old, but thorough discussion.