c语言动态二维数组怎么赋值

510
2024/5/17 15:26:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

动态二维数组的赋值需要先创建数组并分配内存空间,然后逐个元素进行赋值操作。

下面是一个示例代码,演示了如何动态创建一个二维数组并进行赋值操作:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows, cols;
    
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    int **arr = (int **)malloc(rows * sizeof(int *));
    
    for (int i = 0; i < rows; i++) {
        arr[i] = (int *)malloc(cols * sizeof(int));
    }
    
    // Assigning values to the array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr[i][j] = i + j;
        }
    }
    
    // Printing the array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    
    // Freeing the allocated memory
    for (int i = 0; i < rows; i++) {
        free(arr[i]);
    }
    free(arr);
    
    return 0;
}

在这个示例代码中,我们首先要求用户输入数组的行数和列数,然后动态创建一个二维数组。接着我们使用嵌套循环遍历数组,并进行赋值操作。最后我们再次使用嵌套循环打印出数组中的值,然后释放分配的内存空间。

希望这个示例能够帮助你理解动态二维数组的赋值操作。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 利用C语言探究回文结构在密码学中的应用