【问题标题】:Adding elements to an array through a function call [duplicate]通过函数调用将元素添加到数组[重复]
【发布时间】:2016-03-21 00:39:35
【问题描述】:

谁能向我解释为什么这段代码有效:

#include <stdio.h>

void set_array(int array[3]);

int main()
{
    int a[3] = {1, 2, 3};

    set_array(a);

    for (int i = 0; i < 4; i++)
    {
        printf("%d\n", a[i]);
    }
}

void set_array(int array[3])
{
    array[3] = 4;
}

如何通过函数调用将元素添加到数组中?有人可以向我解释一下这里的窗帘后面发生了什么吗?

提前致谢。

【问题讨论】:

  • 这是未定义的行为。
  • 您预计会发生什么?为什么?
  • 我发现这编译得很好,实际上是在a 数组中添加了一个元素。自己试试吧。

标签: c


【解决方案1】:

你不能,你需要使用malloc()分配数组,然后使用realloc()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 2019-08-29
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多