在列表中查找最大值及其地址

Find max value and it's address in the List

C语言。这个函数 (Max_Value) 应该找到最大值及其指向下一个元素的地址。我不知道为什么它不起作用。据说'segmentation fault'。

struct List1 *GetAddress(struct List1* Start, int n)
{
    struct List1 *tmp;
    int count;
    if (n < 0 || n >ListLength(Start))
        return NULL;
    tmp = Start;
    for (count = 0; count < n; count++)
        tmp = tmp -> Next;
    return tmp;
}

int Get_Value(struct List1 *Start, int Number_Element)
{
    struct List1 *Buffer;
    Buffer = GetAddress(Start, Number_Element);
    return Buffer -> Info;
}

void Max_Value(struct List1 *Start)
{
    int Max;
    struct List1 *Max_Address;
    int Count;
    int Amount;
    int tmp;
    Amount = Start -> Info;
    Max = Get_Value(Start, Count);
    Max_Address = GetAddress(Start, Count + 1);
    for (Count = 1; Count < Amount; Count++)
    {        
        tmp = Get_Value(Start, Count);
        if (tmp > Max)
        {
            Max = tmp;
            Max_Address = GetAddress(Start, Count + 1);        
        }        
    }
    printf("\n");
    printf("%d -> %p\n", Max, Max_Address);
}

您在未初始化的情况下将值 Count 发送到 GetAdress,在 C 中,当值未初始化时,它会得到一个超出列表大小的意外数字。鉴于此,您正在尝试访问列表边界之外的内容,这 returns 一个分段错误。

原因是您使用的变量"Count"没有初始值。因此,初始是一个随机数。 如果 "Count" 的初始值大于 List 的大小,GetAddress 将 return 为空。 然后 Get_Value 函数将尝试访问 Null->Info,然后出现分段错误

您有未定义的行为

例如在 Max_Value 中你 Get_Value(Start, Count); 没有初始化 Count,所以很可能

如果使用 n 调用 GetAddress 并评估您取消引用 NULL 的列表的长度,

   if (n < 0 || n >ListLength(Start))

必须

    if (n < 0 || n >= ListLength(Start))

Get_Value你做

Buffer = GetAddress(Start, Number_Element);
return Buffer -> Info;

不检查 GetAddress return 是否为 NULL,因此您可以再次取消引用 NULL


出于可读性原因,我鼓励您不要对局部变量使用大写的名称,而对您定义的类型和全局变量使用大写名称。


你的代码也很复杂,而且很慢,因为你多次抛出列表。一个简单的方法是:

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

struct List {
  int info;
  struct List * next;
};

void Max_Value(struct List * l)
{
  if (l == NULL)
    puts("empty list");
  else {
    struct List * pmax = l;
    int max = l->info;

    while ((l = l->next) != NULL) {
      if (l->info > max)
        pmax = l;
    }

    printf("max value %d (at %p), next is %p\n", max, pmax, pmax->next);
    if (pmax->next != NULL)
      printf("value of the next cell %d\n", pmax->next->info);
  }
}

// to help to make a list

struct List * mk(int v, struct List * n)
{
  struct List * l = malloc(sizeof(struct List));

  l->info = v;
  l->next = n;
  return l;
}

// free resources

void del(struct List * l)
{
  while (l) {
    struct List * n = l->next;

    free(l);
    l = n;
  }
}

int main()
{
  struct List * l;

  l = mk(3, mk(1, mk(4, mk(2, NULL))));
  Max_Value(l);
  del(l);

  l = mk(3, mk(1, mk(4, mk(22, NULL))));
  Max_Value(l);
  del(l);

  return 0;
}