c - C语言中如何正确使用指针?

标签 c pointers

我有这段代码,应该找到数组中的最小整数。我正在学习如何在 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/

相关文章:

c - malloc指针识别

c - 为什么在函数中将 char 数组作为参数传递并尝试在函数内部进行修改会显示段错误?

ios - 获取函数的地址 [Swift 3.0]

c - 在长时间运行的过程中阻止 GUI 卡住

c++ - 我不明白代码的某些部分

c - 初始化线程池

C:图中的代码有什么问题?

c++ - 从 C 访问 C++ 模板

c++ - 在 Visual C++ 中传递给函数时,Sizeof 数组自动更改

c - 指向数组的指针的 sizeof