gpt4 book ai didi

c - 如何打印数组头部的内容并删除

转载 作者:行者123 更新时间:2023-11-30 19:39:18 25 4
gpt4 key购买 nike

我正在尝试创建一个队列,因此我需要将数组反向存储,以便最后一个输入可以是数组的头部,这样我就可以添加内容并删除以前的输入,头部先离开(fifo)。我使用 head_find 函数来计算指针直到最后一个位置,然后删除它并转移。内容

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

//struct node *head;
//struct node *size;
int head;

void reverse_array(int*, int);

int main(){
int x,i,c,length;
char collect;
int rear = -1;
int front = -1;
int *size = NULL;

START:while(1){
printf("Enter operation \n");
scanf("%c",&collect);


switch(collect) {
case 'C' :
printf("create queue\n");
printf("enter size of queue \n");
scanf("%d",&x);
if(x <=0){
printf("Numbers Entered must be non Zero postive Numbers \n");
}
else
printf("Numbers is good \n");
goto START; // leave case

break;
case 'I' :
printf("write vaules\n");
if (front == -1)
// int *size =calloc(x,sizeof(int)); //make size of array
size = (int*)malloc(sizeof(int)*x);
for(i=0;i<x;i++){
scanf("%d",(size+i));
// scanf("%d",&(size[i])); // scan vaules to address
}
/*
for(i=x-1;d=0;i>=0;i--;d++)
int *size2 =calloc(x,sizeof(int));
&(size[d]))=&(size[i]);
for (c = 0; c < x; c++)
printf("%d\n", &(size[c]);
*/
break;
case 'R' :
printf("Read head of queue\n");
/* if (front == - 1)
printf("Queue is empty \n");
*/
head =head_find(&size);
printf("head is %d \n",head);




break;
case 'P' :
printf("print contents=\n");

if (x==0){ // not working as a check
printf("queue is empty\n");
}
else
reverse_array(size,x);
for ( i = 0 ; i < x ; i++ )
printf("size[%d]= %d\n", i,*(size+i));

free(size);



break;
case 'L' :
printf("get length of queue\n");
length=point_ln(size);
printf("Length is %d \n",length);

break;
case 'M' :
printf("Modify length\n");
break;
default:
printf("letter must be in caps \n");
}

}




return 0;
}

int head_find(int *c){
int begin =0;
while(*c != '\0'){
begin --;
c++;



}
return &c;



}

int point_ln(int *p){
int start =0;
while (*p != '\0') {
start++;
p++;
}
return start;

}


void reverse_array(int *size,int x){
int i,d;
int *rev =calloc(x,sizeof(int));

if( rev == NULL )
exit(EXIT_FAILURE);

for ( i = x - 1, d = 0; i >= 0; i--, d++ )
*(rev+d) = *(size+i);

for ( i = 0 ; i< x ; i++)
*(size+i) = *(rev+i);

free(rev);

}

最佳答案

您是否意识到 size 是循环内的局部变量?唯一一次初始化是在case 'I' 中。然后你会泄漏它,下次循环时你将得到 case 'P' 的未初始化值。

将定义移到循环之外:

int *size = NULL;
while(1) {
// ...
}

你的编译器应该警告你在 switch 语句中定义变量。它可能会导致困惑,就像您正在经历的那样。

您在调用 reverse_array 时也遇到问题。您正在传递 &size[i],其中 i 最有可能等于上一个循环中的 x。只需传递大小:

reverse_array( size, x );

但是,我不明白为什么您需要反转数组才能反向打印它。我也不明白为什么要复制整个数组来反转它,而您只需要一个变量来进行交换。

关于c - 如何打印数组头部的内容并删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com