指向char的2D数组

时间:2018-03-28 20:00:02

标签: c arrays string multidimensional-array

我需要声明一个指向chars的指针的二维数组 -

const char* key[4][7] =
{
   {"string1","string2","string3","string4","string5","string6"},
   {"string1","string2","string3","string7"},
   {"string1","string2","string3","string8","string9"},
   {"string1","string2","string3","string10","string11","string12", "string13"}
};
//row is 4 and column is 7 - max number of strings in any array

这个声明是否正确?如何获取每行中的字符串数?我如何访问每一行中的每个元素?

1 个答案:

答案 0 :(得分:0)

下面的代码计算每行中的元素数量并显示它..

    #include <stdio.h>
    int main()
    {
     int count=0;const char* key[4][7] = 
     {{"string1","string2","string3","string4","string5","string6"},
     {"string1","string2","string3","string7"}, 
     {"string1","string2","string3","string8","string9"},{"string1","string2","string3","string10","string11","string12","string13"}};
     for(int i=0;i<4;i++)
     {
          for(int j=0;j<7;j++)
          {
               if(key[i][j]!=NULL)
               count++;
          }  
        printf("count of element in row %d=%d\n",i+1,count);
        count=0;
     }return 0;
    }