How to represent unknown array length in the C language?

In C language, the unknown length of an array can be represented using pointers. Specifically, you can use a pointer as the starting address of the array and not specify a specific array length when defining the pointer.

For example:

int *arr; // 定义一个整型指针arr,表示未知长度的整型数组

int length; // 声明一个变量length,表示数组的长度

printf("请输入数组的长度:");
scanf("%d", &length);

arr = (int*)malloc(length * sizeof(int)); // 根据用户输入的长度动态分配内存

// 使用arr指针访问数组元素
for (int i = 0; i < length; i++) {
    arr[i] = i + 1;
}

// 打印数组元素
for (int i = 0; i < length; i++) {
    printf("%d ", arr[i]);
}

free(arr); // 释放动态分配的内存

The above code starts by defining an integer pointer arr, then dynamically allocates memory space for length integer variables using the malloc function, assigning the starting address to arr. You can then access and manipulate array elements through the arr pointer. Finally, the free function is used to release the dynamically allocated memory space.

bannerAds