C函数和数组

时间:2017-05-22 23:04:31

标签: c arrays pointers

我正在学习C编程并将数组传递给多个函数,不确定我的数组何时以及为什么被某些东西覆盖,帮助我调试并发现我在代码中的错误:

#include <stdio.h>

int insertNumbers(int *numbers, int howManny){
    int i;

    for(i=0; i< howManny; i++){
        printf("Insert number:");
        scanf("%d", &numbers[i]);
    }
    printf("\nNumbers :(insertNumbers function)\n");
    for (int i = 0; i < howManny; ++i) {
        printf("%d: %d\n",i, numbers[i]);
    }
    return  *numbers;
}

int add(int *numbers, int howManny){
    int sum = 0;
    for (int i = 0; i < howManny; ++i) {
        sum = sum + numbers[i];
    }
    return sum;
}

void printArray(int *numbers, int howManny){
    printf("\nNumbers:(print array function)\n");
    for (int i = 0; i < howManny; ++i) {
        printf("%d: %d\n",i, numbers[i]);
    }
}

int main(){
    int numbers, howManny, sum = 0, numbersArray;
    printf("How manny numbers do you want?");
    scanf("%d", &howManny);

    numbersArray = insertNumbers(&numbers, howManny);

    sum = add(&numbers, howManny);
    printf("Total sum is: %d",sum);

    printArray( &numbersArray, howManny);


    return 0;
}

结果是

How manny numbers do you want?3
3
Insert number:10
10
Insert number:20
20
Insert number:30
30

Numbers :(insertNumbers function)
0: 10
1: 20
2: 30
Total sum is: 60
Numbers:(print array function)
0: 10
1: 3
2: 10

看起来我的数组被某处覆盖但不确定何时以及为何

即使我尝试使用

printArray( &numbers, howManny);

仍然没有工作,但得到10,10,50个值

1 个答案:

答案 0 :(得分:2)

您的数组尚未在编译时创建。此外,数组大小在程序的运行时给出。因此,数组不能是静态的,因此必须动态分配并在最后释放,以便正常工作。

话虽如此,我在这里为你想要实现的目标写了一个简单的解决方案。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void insertNumbers(int *numbers, int howManny){
    int i;

    for(i=0; i< howManny; i++){
        printf("Insert number:");
        scanf("%d", &numbers[i]);
    }
    printf("\nNumbers :(insertNumbers function)\n");
    for (int i = 0; i < howManny; ++i) {
        printf("%d: %d\n",i, numbers[i]);
    }
}

int add(int *numbers, int howManny){
    int sum = 0;
    for (int i = 0; i < howManny; ++i) {
        sum = sum + numbers[i];
    }
    return sum;
}

void printArray(const int *numbers, int howManny){
    printf("\nNumbers:(print array function)\n");
    for (int i = 0; i < howManny; ++i) {
        printf("%d: %d\n",i, numbers[i]);
    }
}

int main(){

    int *numbers, howManny;

    printf("How manny numbers do you want?");
    scanf("%d", &howManny);

    // allocate memory (dynamic allocation)
    numbers = (int *)malloc(sizeof(int) * howManny);

    // validate memory allocation
    assert(numbers != NULL);

    // numbers is modified and returned by reference
    insertNumbers(numbers, howManny);

    printf("Total sum is: %d", add(numbers, howManny));
    printArray(numbers, howManny);

    // free dynamic allocation
    free(numbers);

    return 0;
}