【发布时间】:2019-06-22 02:34:46
【问题描述】:
数据结构中的函数调用
我想删除序列表中的第i个元素,在main函数中调用自己定义的DelList函数删除,但是编译后无法按预期打印出被删除元素的值. 第 48 行之前的代码工作正常,但似乎无法调用 DelList 函数,导致没有打印已删除的元素。 调用 DelList 函数有问题吗?还是DelList函数的返回有问题? 谢谢
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
typedef int ElemType; /*Assume that the data elements in the sequence table
are integers*/
typedef struct {
ElemType elem[MAXSIZE];
int last;
}SeqList;
int DelList(SeqList *L, int i, ElemType *e)
/*The i-th data element is deleted in the sequence table L, and its value is returned with the pointer parameter e. The legal value of i is 1 ≤ i ≤ L. last +1 */
{
int k;
if ((i < 1) || (i > L->last + 1))
{
printf("Deleting the location is not legal!");
return(ERROR);
}
*e = L->elem[i - 1]; /* Store the deleted element in the variable pointed to by e*/
for (k = i; i <= L->last; k++)
L->elem[k - 1] = L->elem[k]; /*Move the following elements forward*/
L->last--;
return(OK);
}
void main()
{
SeqList *l;
int p, r;
int *q;
int i;
l = (SeqList*)malloc(sizeof(SeqList));
q = (int*)malloc(sizeof(int));
printf("Please enter the length :");
scanf("%d", &r);
l->last = r - 1;
printf("Please enter the value of each element:\n");
for (i = 0; i <= l->last; i++)
{
scanf("%d", &l->elem[i]);
}
printf("Please enter the location of the element you want to delete:\n");
scanf("%d", &p);
DelList(l, p, q);
printf("The deleted element value is:%d\n", *q);
}
编译可以通过但不是我想要的结果
【问题讨论】:
-
这是纯C!!!我将删除 C++ 标签,这样你就不会被烧毁了
-
您是在 Windows 上运行它吗?我在 OpenSUSE 上编译我们的代码很好,但是当我在 Windows 上运行它时,我注意到 Windows Defender 正在阻止程序执行。
-
所以有一个有趣的行为——当我给它删除位置的最大值时,代码起作用了。 DelList 被调用——我正在使用 printf 调试来证明——但你的 for (k = i; i last; k++) 不适用于小于最大值的值。
-
@jhelphenstine 你可以查看我的答案以获得解释。
标签: c data-structures