温馨提示×

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

小亿
84
2024-05-30 15:26:14
栏目: 编程语言

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

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

#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;
}

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

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

0