C:二维数组的大小 [英] C: Size of two dimensional array

查看:500
本文介绍了C:二维数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来计算二维数组的行和列.看来我无法计数列?

I need some help counting the rows and columns of a two dimensional array. It seems like I can't count columns?

#include <stdio.h>

int main() {

char result[10][7] = {

    {'1','X','2','X','2','1','1'},
    {'X','1','1','2','2','1','1'},
    {'X','1','1','2','2','1','1'},
    {'1','X','2','X','2','2','2'},
    {'1','X','1','X','1','X','2'},
    {'1','X','2','X','2','1','1'},
    {'1','X','2','2','1','X','1'},
    {'1','X','2','X','2','1','X'},
    {'1','1','1','X','2','2','1'},
    {'1','X','2','X','2','1','1'}

};

int row = sizeof(result) / sizeof(result[0]);
int column = sizeof(result[0])/row;

printf("Number of rows: %d\n", row);
printf("Number of columns: %d\n", column);

}

输出:
行数:10
列数:0

Output:
Number of rows: 10
Number of columns: 0

推荐答案

这是整数除法的问题!

int column = sizeof(result[0])/row;

应该是

int column = 7 / 10;

并以整数除法7/10==0.

您想要做的是除以一行的长度,例如sizeof(result[0])乘以该行一个元素的大小,例如. sizeof(result[0][0]):

What you want to do is divide the length of one row, eg. sizeof(result[0]) by the size of one element of that row, eg. sizeof(result[0][0]):

int column = sizeof(result[0])/sizeof(result[0][0]);

这篇关于C:二维数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆