我有这段代码,应该找到数组中的最小整数。我正在学习如何在 C 中使用指针,但我的代码无法编译,但我不知道为什么。我不仅仅是想知道答案,还想知道为什么我做错了或者我的思维过程是如何错误的。
我认为*p_min
会返回地址内的值。
我得到的错误:
error: invalid type argument of ‘unary *’ (have ‘int’)
Warning: return makes pointer from integer without a cast
p 在函数外部声明为 int *p;
代码:
int *find_smallest(int a[], int N)
{
int *p_min;
for (p = &a[0]; p < &a[N]; p++)
{
if (*p[1] < *p[0]) {
p_min = &p[1];
return *p_min;
} else {
p_min = &p[0];
return *p_min;
}
}
}
最佳答案
不太确定您在使用比较逻辑做什么。最直接的方法是从第一个元素开始,然后依次检查其余元素,保留较小元素的索引。我的代码将是这样的:
int *find_smallest(int a[], int N)
{
/* Make sure the input is valid */
if (a && N > 0)
{
int i, N_min = 0;
/* Check the rest of the elements */
for (i = 1; i < N; i++)
{
/* If this one is lower, save the index */
if (a[i] < a[N_min])
N_min = i;
}
/* Return pointer to minimum */
return a + N_min;
}
/* Return NULL to indicate an error */
return NULL;
}
关于c - C语言中如何正确使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257307/