Dynamically apply for space malloc function

 In daily programming, we often encounter this problem. We want to use a variable as an array subscript, because we want the person using the program to input this variable to determine the size of the array.

E.g:

#include<stdio.h>
int main()
{
    int n = 0;
    scanf("%d", &n);
    int arr[n] = { 0 };
    return 0;
}

At this time, we need to dynamically apply for space.

 

  The above are the usage rules of malloc that I found on MSDN:

1. The parameter part is the number of bytes to allocate.

2. Since the return value of the malloc function is void, we need to cast the type when using it.

Let's try it out with a problem:

 The title has specified variable names:

 1.n int integer maximum number of digits
 2. return int integer one-dimensional array
 3.return int* returnSize Return the number of rows in the array

int* printNumbers(int n, int* returnSize ) 
{
*returnSize = pow(10, n) - 1; //确定最大的数字
int *arr = (int *)malloc(sizeof(int)*(*returnSize));//申请足够大小的空间
//         强制类型转换   要分配的内存大小由returnSize决定
for (int i = 0; i < *returnSize; i++)
{
arr[i] = i+1;//下标从0开始,而数值从1开始
}
return arr;
}

 Thank you for being here, that's all for today's sharing!

Guess you like

Origin blog.csdn.net/m0_60653728/article/details/122799685