-1

我正在编写一个程序来对一组数字执行 shellsort。我首先必须生成将执行 shellsort 的数字序列。此函数用于生成小于要排序的数组长度的 2^p*3^q 形式的数字。然后我对刚刚生成的序列数组进行排序。这是我的实现:

long * Generate_2p3q_Seq(int length, int *seq_size) {
  int ind = 0;
  long * arr[1000];
  int product;
  int power = 1;
  while (power < length) {
    product = power;
    while (product < length) {
      arr[ind] = product;
      product *= 3;
      ind++;
    }
    power *= 2;
  }
  int i, j, k;
  for (i = 0; i < ind; ++i) {
    for (j = i + 1; j < ind; ++j)
    {
      if (arr[i] > arr[j])
      {
        k =  arr[i];
        arr[i] = arr[j];
        arr[j] = k;
      }
    }
  }
  *seq_size = ind;
  for (int count = 0; count < ind; count++) {
    printf("arr[%d] = %li\n", count, arr[count]);
  }
  return arr;
}

该代码旨在返回一个 long * 数组并将 seq_size 设置为序列数组的长度。例如,如果给定一个包含 16 个整数的数组进行排序,则此处生成的序列数组应该是 8 个整数(1、2、3、4、6、9、8、12)并且 seq_size 应该等于 8。相信我对指针的理解是错误的,因为我的终端输出如下所示:

sequence.c: In function ‘Generate_2p3q_Seq’:
sequence.c:14:16: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
       arr[ind] = product;
                ^
sequence.c:26:11: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
         k =  arr[i];
           ^
sequence.c:28:16: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
         arr[j] = k;
                ^
sequence.c:34:25: warning: format ‘%li’ expects argument of type ‘long int’, but argument 3 has type ‘long int *’ [-Wformat=]
     printf("arr[%d] = %li\n", count, arr[count]);
                       ~~^            ~~~~~~~~~~
                       %ln
sequence.c:36:10: warning: return from incompatible pointer type [-Wincompatible-pointer-types]
   return arr;
          ^~~
sequence.c:36:10: warning: function returns address of local variable [-Wreturn-local-addr]

但是,我不确定如何更改它以使其正常工作。我将此函数称为:

  long * sequence = Generate_2p3q_Seq(size, &seq_size);

如果我遗漏了任何信息,请告诉我,我非常感谢任何帮助。

4

2 回答 2

1

这里有两个主要问题。首先,您声明arrlong *arr[1000],这意味着它是指向 的指针 long数组,而不是 的数组long。这就是为什么你要在指针和整数之间进行转换。

定义数组的正确方法long是:

long arr[1000];

但这会导致第二个问题,即您正在返回一个指向局部变量的指针。当函数返回时,其局部变量超出范围,因此返回的指针不再指向有效内存。

要解决此问题,请声明arr为指针并使用malloc为它动态分配内存:

long *arr = malloc((product * power) * sizeof *arr);
if (!arr) {
    perror("malloc failed");
    exit(1);
}

然后你可以返回 的值arr,它指向动态分配的内存。

于 2019-02-17T17:24:37.600 回答
0

将指向数组的指针作为附加参数传递,并对其进行操作。

void Generate_2p3q_Seq(long * arr, int length, int *seq_size) {
    // Method stores result in pre-initialized arr.
}

// Call with:

long arr[1000];
Generate_2p3q_Seq(arr, length, seq_size)

// Result stored correctly in arr.
于 2019-02-17T17:15:40.813 回答