C:通过指针打印数组会给出错误的数字

时间:2016-02-12 18:04:52

标签: c arrays pointers

我刚刚开始学习C代码,并且我已经开始练习创建您可以在我的代码中看到的两个函数createData()udskriv() {{1}应该使用用户输入创建一个数组,createData方法应该使用指针打印它。

然而,我的代码只给了我1或2个正确的数字,然后通常是0和1个非常高的数字(如10位数)打印时。通过在udskriv方法中运行循环,我能够通过实现它而无需函数来实现它,但我无法使用它们。

我有一些Java经验,可以帮助您解释我为什么做错了。

main

3 个答案:

答案 0 :(得分:2)

您正在返回指向本地数据的指针。函数test中的变量createData是一个局部变量,在技术上称为"存储类auto"。当函数返回时,用于test的内存可能用于其他目的。

答案 1 :(得分:1)

您无法返回指向局部变量的指针。函数退出时,局部变量被破坏。之一:

  • 在函数调用中传入缓冲区
  • malloc你要返回的数组(调用者必须释放它)

答案 2 :(得分:0)

Now it works. I've added a memory allocation for your variable (test) and I've modified the return line of the function createData. The reason that the initial code does not works is that (test) is a local variable and will be destroyed after exiting the function createData.

<script>
  function myf() {
    var size = document.getElementById('mycontroller').value;
    document.getElementById("mytext").style.fontSize = size + "px";
  }

</script>