尝试使用malloc时出现分段错误
所以,我有这个结构尝试使用malloc时出现分段错误,c,arrays,dynamic,struct,malloc,C,Arrays,Dynamic,Struct,Malloc,所以,我有这个结构 typedef struct queue { int size; //size of the array int inicio; //first position that contains a value in the array int tamanho; //number of actual values in the array int *valores; //array } QUEUE; 我用这个函数处理这个结构 int enqu
typedef struct queue {
int size; //size of the array
int inicio; //first position that contains a value in the array
int tamanho; //number of actual values in the array
int *valores; //array
} QUEUE;
我用这个函数处理这个结构
int enqueue (QUEUE *q, int x){
if(q -> inicio + q -> tamanho < q -> size){
q -> valores[q -> inicio + q -> tamanho] = x;
q -> tamanho++;
}
else if (q -> tamanho < q -> size){
for(int i = 0; i < q -> tamanho; i++){
q -> valores[i] = q -> valores[q -> inicio + i];
}
q -> inicio = 0;
q -> valores[q -> tamanho++] = x;
}
else{
int *new = malloc(q -> size * 2 * sizeof(int));
for(int i = 0; i < q -> size; i++){
new[i] = q -> valores[i];
}
new[q -> size] = x;
q -> size *= 2;
free(q -> valores);
q -> valores = new;
}
return 0;
}
int排队(队列*q,int x){
如果(q->inicio+q->tamanhosize){
q->valores[q->inicio+q->tamanho]=x;
q->tamanho++;
}
否则如果(q->tamanhosize){
对于(inti=0;itamanho;i++){
q->valores[i]=q->valores[q->inicio+i];
}
q->inicio=0;
q->valores[q->tamanho++]=x;
}
否则{
int*new=malloc(q->size*2*sizeof(int));
对于(int i=0;isize;i++){
新[i]=q->valores[i];
}
新[q->尺寸]=x;
q->尺寸*=2;
自由(q->valores);
q->valores=新;
}
返回0;
}
当您获取列表中的元素时,您从Begging中获取它们,因此Begging中没有任何内容
因此,这个函数应该在有空间的情况下将值添加到末尾,将所有内容推送到begging,如果begging中有空的空间,则在末尾添加值,如果需要更多空间,则扩展数组。问题是。。。它立即发出一个分段错误。如果我试图在别人乞求的时候打印出某样东西,它就不行了
我真的迷路了。在enqueue()
函数中为q->valores
分配内存。分配它
int enqueue (QUEUE *q, int x){
q -> valores = malloc(sizeof(QUEUE));/*check yourself how much memory you need */
/* remaining same code */
}
在
q->valores[q->inicio+q->tamanho]=x
valores
是结构的指针成员,您是否为q->valores
分配了内存?我不这么认为。问题不在那里。那一点管用。q是一个参数,它已经初始化了。问题出在第三个方面。前两个workshow us您如何使用参数调用enqueue()
:虽然C中没有公认的命名标准,但所有大写名称都应该是宏。不要将它们用于类型、变量等;q1.1尺寸=3;q1.inicio=0;q1.tamanho=0;排队(&q1,1);排队(&q1,2);排队(&q1,3);排队(&q1,4);它一直工作到最后一个