【发布时间】:2020-10-10 18:40:07
【问题描述】:
我编写了一个函数来创建一个随机值的动态数组,另一个函数创建一个由前一个数组的唯一值组成的新数组。使用的算法正确计算唯一值。但是,我在打印所有值时遇到了问题。在下面的示例中,程序打印了7 2 12714320 4 5 而不是7 2 4 5 6。
这是可以测试的程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *delduplicate(int *v, int size_old, int *size_new);
main()
{
int n;
int *norepeat;
float *results;
int dim, size_norepeat, i;
int a[7] = {7,2,2,4,5,6,7};
norepeat = delduplicate(a, 7, &size_norepeat);
for (int i = 0; i < size_norepeat; i++)
printf("%d ", norepeat[i]);
}
// delduplicate function
int *delduplicate(int *v, int size_old, int *size_new)
{
int i, j, k = 1, uniques = 1, repeats, *new_v, temp;
// count the number of unique elements
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; is_unique && j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
uniques++;
}
*size_new = uniques;
// create new array of unique elements
new_v = (int*) malloc(*size_new * sizeof(int));
// fill new array with unique elements
new_v[0] = v[0];
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
new_v[k] = v[i];
k++;
}
return new_v;
}
问题应该发生在这里:
// fill new array with unique elements
new_v[0] = v[0];
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
new_v[k] = v[i];
k++;
}
【问题讨论】:
-
什么是“问题”?
-
当发布的代码通过编译器运行时,会输出一长串警告。从以下开始:untitled1.c:7:1: warning: return type defaults to ‘int’ [-Wimplicit-int] 编译时,始终启用警告,然后修复这些警告。 (对于
gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果。 -
注意:编译器输出的最后一行可能是:
Compilation finished successfully.,但这仅意味着编译器对问题应用了一些解决方法,而不是生成了正确的代码。 -
OT:为了便于阅读和理解:1)请遵循公理:每行只有一个语句,并且(最多)每个语句一个变量声明。
-
OT:关于:
new_v = (int*) malloc(*size_new * sizeof(int));1) 函数:malloc()需要类型参数:size_t但size_new是一个整数。 2) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱并且容易出错。 3) 始终检查 (!=NULL) 返回值以确保操作成功。