2016-11-16 111 views
0

我有兩個字符數組,我想做一個2維數組。 但字符值似乎造成了一個問題,就像我試圖在2D數組中初始化它們一樣。如何在C中初始化這個二維數組?

什麼是初始化這種類型的數組的正確方法? 函數「trumplar()」可以正常工作,也可以像我期望的那樣工作。

2D字符數組x [22] [22]函數「trumpsterFire()」無法正確初始化。

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

void trumplar(){ 
int len = 22; 
     char a[25]={0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x3d,0x76,0x1e,0x38,0x38,0x6d,0x00}; 
     char L[25]="abcdefghjlpsS"; 
    int i; 
    for (i = 0; i <=len; i++){ 
     char hit=L[i]; 
     char urd=a[i]; 
     printf("The %d, Value of a is:%c\t Hex val: %c\n",i,hit,urd); 
     } 
} 

void trumptsterFire(){ 
    //int xlen = 22; 
char x[22][22]={ 
    {0x3f,0},{0x6,1},{0x5b,2}, 
    {0x4f,3},{0x66,4},{0x6d,5}, 
    {0x7d,6},{0x7,7},{0x7f,8}, 
    {0x6f,9},{0x77,a},{0x7c,b}, 
    {0x39,c},{0x5e,d},{0x79,e}, 
    {0x71,f},{0x3d,g},{0x76,h} 
    ,{0x1e,j},{0x38,l},{0x38,p}, 
    {0x6d,s},{0x00,S} 
    }; 
    }  

int main(){ 
    trumplar(); 
trumptsterFire(); 
    return 0; 
    } 
+0

您是否將最後一個'\ 0'元素添加到數組? –

+1

您的陣列尺寸沒有多大意義。你已經有了'char x [22] [22]'(由22個字符組成的22個數組的數組),然後是一個匹配char x [23] [2]的初始化列表(2個字符的23個數組) ...(忽略缺失的單引號) – Dmitri

回答

2

使用單個qoute(')來分配一個字符。

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

     void trumplar(){ 
     int len = 22; 
       char a[25]={0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x3d,0x76,0x1e,0x38,0x38,0x6d,0x00}; 
       char L[25]="abcdefghjlpsS"; 
      int i; 
      for (i = 0; i <=len; i++){ 
       char hit=L[i]; 
       char urd=a[i]; 
       printf("The %d, Value of a is:%c\t Hex val: %c\n",i,hit,urd); 
       } 
     } 

     void trumptsterFire(){ 
      //int xlen = 22; 
     char x[22][22]={ 
      {0x3f,'0'},{0x6,'1'},{0x5b,'2'}, 
      {0x4f,'3'},{0x66,'4'},{0x6d,'5'}, 
      {0x7d,'6'},{0x7,'7'},{0x7f,'8'}, 
      {0x6f,'9'},{0x77,'a'},{0x7c,'b'}, 
      {0x39,'c'},{0x5e,'d'},{0x79,'e'}, 
      {0x71,'f'},{0x3d,'g'},{0x76,'h'} 
      ,{0x1e,'j'},{0x38,'l'},{0x38,'p'}, 
      {0x6d,'s'},{0x00,'S'} 
      }; 
      }  

     int main(){ 
      trumplar(); 
     trumptsterFire(); 
      return 0 

    ; 
     } 
+0

\ 0字符不是必需的,我只是忽略它。 – j0h