How can I allocate memory for array inside a function

前端 未结 4 1608
逝去的感伤
逝去的感伤 2020-12-21 19:41

I am trying to receive a number from the user. And create an array with that number, but, inside a function. Here are my few attempts, I get into run time errors. Help is ve

4条回答
  •  青春惊慌失措
    2020-12-21 20:05

    Some typos in your code,

    p = (int *)malloc(num * sizeof(int));
    

    should be

    pp = (int *)...
    

    Your free(pp); is what is causing it to not work chiefly, you do not want to call that or the memory you allocated will not be saved. Also the memory of pp is essentially "lost" at the end of the function call as method parameter to Init p is a value copy not exact reference to main's version of p, thus when Init returns, the changes to p are 'lost'.

    simply do: p = Init(); and in init return pp;

    Exp: This line p = pp, sets variable p to point to the memory allocated by pp, thus a free of pp is a free to p as well. I am not sure if returning an address to memory is always considered good practice, as you have to ensure it is freed, but for your program it would work.

提交回复
热议问题