在列表中找到最大值和它的地址。

问题描述 投票:0回答:1

C语言。这个函数(Max_Value)应该是找到最大值和它的地址到下一个元素。我不知道为什么它不工作。据说是 "分段故障"。

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);
}
c max memory-address
1个回答
1
投票

你发送的值是 CountGetAdress 没有被初始化,在C语言中,当一个值没有被初始化时,它会得到一个意外的数字,这个数字超过了你的列表的大小。鉴于此,你试图访问到列表的边界之外,这将返回一个分段故障。


0
投票

原因是你使用的变量 "Count "没有初始值。因此,初始是一个随机数。如果 "Count "的初始值大于List的大小,GetAddress将返回null。然后,Get_Value函数将尝试访问Null->Info,然后你得到了分段故障。


0
投票

你有未定义的行为

例如,在 最大值 你做 Get_Value(Start, Count); 而没有初始化 Count所以很可能

如果 GetAddress 被称为 n重视你所推断的NULL的列表长度。

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

必须

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

Get_Value 你做

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

不查 GetAddress 返回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;
}
© www.soinside.com 2019 - 2024. All rights reserved.