[英]Problems concerning pointers and malloc in C90
在C语言方面,我是一个新手,在内存分配和指针方面似乎有一些问题。 对于我的任务,我们必须使用数组创建动态集的ADT,并且为此,我们需要大量使用指针,而我发现这有点难于理解。
我创建了一个结构来充当场景
struct Set{
int arrelement; //the 'size' of the array
int * arrvalue;; //the array
}
typedef struct Set *SetArray;
当我要使用诸如Add(向集合中添加唯一元素)或Cardinality(其中程序向我显示集合中元素总数)之类的函数时,就会出现问题。 添加两次以上后,添加似乎会使我的程序崩溃,并尝试检索存储的数据提供的垃圾变量。
这是相关功能的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Array.h"
int size = 1; // similar to arrelement, to be used for realloc
SetArray Create(){ // to allocate memory for the set
SetArray sptr;
sptr = malloc(sizeof(struct Set));
sptr->arrvalue = malloc(sizeof(struct Set));
sptr->arrelement = 1;
return sptr;
}
SetArray Add(SetArray sptr, int x){
if(Is_Element_Of(x, sptr)){ //function to keep elements in set unique.
//Function works, which brings me to
//believe values are being stored
puts("Value already exists, enter a unique value");
}
else{
if(sptr == NULL){
puts("Memory Allocation Failed. Shutting down.");
exit(EXIT_FAILURE);
}
}
sptr = realloc(sptr, size*sizeof(struct Set)); //reallocate memory
//for the
//new element
sptr->arrvalue[sptr->arrelement] = x;
sptr->arrelement++;
size++;
return sptr;
}
SetArray Remove(SetArray sptr, int x){
if(sptr == NULL){
puts("Memory Allocation Failed. Shutting down.");
exit(EXIT_FAILURE);
}
else if(!Is_Element_Of(x, sptr)){
puts("Value is not in set");
}
else if(sptr->arrvalue == NULL){
puts("Set is empty. Cannot remove that which does not exist");
}
else{
sptr = realloc(sptr, size*sizeof(struct Set));
sptr->arrvalue[sptr->arrelement] = '\0';
sptr->arrelement--;
size--;
}
return sptr;
}
SetArray Clear(SetArray sptr){
if(sptr == NULL){
puts("Memory Allocation Failed. Shutting down.");
exit(EXIT_FAILURE);
}
int i;
for(i = 0; i < sptr->arrelement; i++){
sptr->arrvalue[i] = '\0';
}
return sptr;
}
另外,不确定是否相关,但以防万一,这里是函数Is_Element_Of
int Is_Element_Of(int x, SetArray sptr){
if(sptr == NULL){
puts("Memory Allocation Failed. Shutting down.");
exit(EXIT_FAILURE);
}
int flag = 0;
int i;
for(i = 0; i < sptr->arrelement; i++){
if(sptr->arrvalue[i] == x){
flag = 1;
}
}
return flag;
}
请原谅我的任何错误,但这是我第一次问我,我竭尽全力使一切都井井有条。
感谢您的阅读。
当您要重新分配它所包含的数组时,您正在重新分配错误的指针,并且将指针重新分配给父集合。
sptr = realloc(sptr, size*sizeof(struct Set));
应该
sptr->arrvalue = realloc(sptr->arrvalue, (sptr->arrelement+1)*sizeof(int));
我想你的主要问题是这样的:
sptr->arrvalue = malloc(sizeof(struct Set));
由于arravlue是int *,请尝试以下操作:
sptr->arrvalue = malloc(sizeof(int));
编辑:重新分配相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.