我正在尝试使用 C 中的抽象数据类型 (ADT) 创建一个数组,但我似乎遇到了逻辑错误。虽然不存在编译问题,但输出并不符合预期。我在下面提供了我的代码:
#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;
}
我当前得到的输出是:
we are running setval now
00we are running show now
enter element 0 -
但是,预期输出应该是:
We are running setVal now
Enter element 0 - 1
Enter element 1 - 2
We are running show now
1
2
任何识别逻辑错误的帮助将不胜感激。谢谢!
OP代码中有一些特殊问题:
setVal()
中,n = a->ptr[i];
行应该是 a->ptr[i] = n;
,以便将值写入数组。show()
中,调用 printf
应添加换行符:printf("%d\n",(a->ptr[i]));
。main()
中,show(&marks);
和setVal(&marks);
行应该切换(先设置,然后显示)。通过这些更新,结果符合预期。
在更概念的层面上,要创建抽象数据类型,
myArray
的定义不应该在数据类型实现之外可见。参见例如这个问题/答案是一个古老但彻底的讨论。