繁体   English   中英

使用带数组的指针时遇到麻烦

[英]Trouble using pointers with array

我是C的新手并且指针有问题。 我无法在线或通过我的同行找到答案,所以我在这里。

我被赋予了一个任务:

  • 创建一个包含20个随机整数的数组
  • 打印出整数
  • 按升序对数组进行排序
  • 再次打印出来

当我用GCC编译程序并运行时,我得到了一个分段错误。 当我尝试在sort函数中设置number[i]number[k]的值时,我已经缩小了它的范围。 任何帮助,将不胜感激。

#include <stdio.h>

void sort(int* number, int n){
     /*Sort the given array number , of length n*/
    int temp, min;
    int i, k;
    for(i=0; i<n; i++){
        min = i;
        for(k=i+1; k<n; k++){
            if(number[k]<min){
                min = k;
            }
        }
        temp = number[i];
        number[i] = number[k];
        number[k] = temp;
    }   
}

int main(){
    /*Declare an integer n and assign it a value of 20.*/
    int n=20;

    /*Allocate memory for an array of n integers using malloc.*/
    int *array = malloc(n * sizeof(array));

    /*Fill this array with random numbers, using rand().*/
    srand(time(NULL));
    int i;
    for(i=0; i<n; i++){
        array[i] = rand()%1000+1;
    }

    /*Print the contents of the array.*/
    for(i=0; i<n; i++){
        printf("%d\n", array[i]);
    }

    /*Pass this array along with n to the sort() function of part a.*/
    sort(&array, 20);

    /*Print the contents of the array.*/
    printf("\n");
    for(i=0; i<n; i++){
        printf("%d\n", array[i]);
    }

    return 0;
}

以下是我得到的编译错误:

Q3.c:在函数中:

Q3.c:31:警告:隐式声明函数âmallocâ

Q3.c:31:警告:内置函数âmalloc的不兼容的隐式声明

Q3.c:34:警告:隐式声明函数âsrandâ

Q3.c:34:警告:隐式声明函数âtimeâ

Q3.c:37:警告:隐式声明函数“

Q3.c:46:警告:从不兼容的指针类型传递âsortâ的参数1

Q3.c:9:注意:预期âint*â,但参数类型为âint**â

在您交换元素的位置,

temp = number[i];
number[i] = number[k];
number[k] = temp;

k == n因为它是在结束之后

for(k=i+1; k<n; k++){

你的意思是在交换中使用min而不是k

main

int *array = malloc(n * sizeof(array));

分配足够的空间n指针int ,20没有空间int 那应该是

int *array = malloc(n * sizeof *array);

关于编译器警告/错误,

#include <stdlib.h>

并打电话

sort(array, 20);

而不是传递&array

array是一个int* ,你的sort函数期望一个int* ,你传递&array ,int指针的地址

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM