警告:赋值操作会根据指针生成整数,而无需在Shellsort算法中强制转换

时间:2019-02-17 17:06:44

标签: c arrays sorting pointers shellsort

我正在编写一个程序来对数字数组执行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;
}

该代码用于返回一个长*数组,并将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);

请让我知道是否遗漏了任何信息,非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

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

long arr[1000];

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

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

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

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

答案 1 :(得分: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.