c - 警告:赋值从指针中生成整数,而无需在 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;
}
该代码旨在返回一个 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);
如果我遗漏了任何信息,请告诉我,我非常感谢任何帮助。
解决方案
这里有两个主要问题。首先,您声明arr
为long *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
,它指向动态分配的内存。
推荐阅读
- html - 将两个值绑定到模型中以供选择框
- html - CSS,将样式设置为 div 子级
- python - 如何在 Python Gekko 优化中强制执行二进制(或整数)变量?
- database - 是否可以在 oracle 中使用 SYS_REFCURSOR 打印 1,2,3......n?
- java - 表分组每小时和平均值
- windows - "\\?\" 路径/目录指向哪里?
- python - 将自定义模板标签扩展到 Django 中的其他模板
- sql - postgresql 左连接和排序
- python-3.x - 有没有办法将变量 client.service.methods 与 suds-py3 一起使用?
- c++ - 使用 ioctl 在 C++ 中以编程方式添加路由