c - 打印 0 而不是指定数字的基本功能 C

标签 c

我有这个基本代码,旨在询问用户要输入多少个整数,让用户为每个整数输入指定的数字,然后重新打印用户输入的整数,除了不打印它只是打印的整数0个

int getInts(int * integersArray, int numInput);

int main() {
    int * integersArray;
    int numInput;
    int i;

    numInput = getInts(integersArray, numInput);

    for (i = 0; i < numInput; i++) {
        printf("%d ",integersArray[i]);
    }

    return 0;
}


int getInts(int * integersArray, int numInput) {
    int i;

    printf("Please enter the number of integers you want to input\n");
    scanf("%d", &numInput);

    integersArray = (int *) malloc(sizeof(int) * numInput);

    for (i = 0; i < numInput; i++) {
        printf("please enter integer %d: ", i+1);
        scanf("%d", &(integersArray[i]));
    }

    return numInput;
}

最佳答案

移动这些行:

printf("Please enter the number of integers you want to input\n");
scanf("%d", &numInput);
integersArray = (int *) malloc(sizeof(int) * numInput);

main , 在你打电话之前 getInts .

你需要这个的原因是 getInts收到 integersArray 的副本(即指针的副本)和 getInts 内的赋值只修改副本,integersArray主要保持完整。

关于c - 打印 0 而不是指定数字的基本功能 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594496/

相关文章:

c - pthreads 的 Readers-Writers 问题导致只有 1 个读者

c - 如何在 switch 语句的 case 字段中使用变量?

c - 返回结构

java - JNA:void** 和 void* 之间的转换

c - c 中的包装函数

c - glib 是否可以以不显眼的方式使用?

c语言数据类型运算规则

c - 正在存储截断的值

c - 错误 C2040 : 'void *()' differs in levels of indirection from 'int ()'

c - I2C 用户空间读/写问题