-8

i have 1d Array and i have to copy in 2D Array like this

sDaysInMth[0] 31
sDaysInMth[1] 28
sDaysInMth[2] 31
sDaysInMth[3] 30
sDaysInMth[4] 31
sDaysInMth[5] 30
sDaysInMth[6] 31
sDaysInMth[7] 31
sDaysInMth[8] 30
sDaysInMth[9] 31
sDaysInMth[10] 30
sDaysInMth[11] 31

but Having problem in this code? i am not able to get correct answer.

    static char pvtsWsMthDayTab[24]="312831303130313130313031";
     char sDaysInMth[12][2] ;
     static char pvtsWsNbrDyMth[3]="";
     int i=0 , j = 0 ;

    memset(pvtsWsNbrDyMth,'\0', sizeof(pvtsWsNbrDyMth));
    memset(sDaysInMth, '\0', sizeof(sDaysInMth));    
     for(i=0; i< 12; i++)
     {
        memcpy(sDaysInMth[i], pvtsWsMthDayTab+(i*2), 2);

     }

    for(i=0;i<12;i++)
    {
        printf("%s ",sDaysInMth[i]); /* printing 2D array*/

        printf("\n");
     }
MD XF
  • 7,860
  • 7
  • 40
  • 71
  • I am not sure I understand the question, please show what you have tried. – sergej Oct 07 '15 at 08:32
  • I'm assuming op wants to split the array into "31", "28", "31", "30", " ... etc. – Component 10 Oct 07 '15 at 08:33
  • 1
    Welcome to stack overflow. Don't start your question title with how you feel, but rather a question or the problem you're facing. Your question is unclear and copying an array is fairly simple and has been answered many times. Also tagging C and C++ (multiple languages) is usually discouraged. – aslg Oct 07 '15 at 08:34
  • The size of your array is wrong, your compiler should report excess of elements if warnings were enabled. – Iharob Al Asimi Oct 07 '15 at 08:34
  • ... similarly the target array will need to be of size **3** occurring 12 times. – Weather Vane Oct 07 '15 at 08:39
  • [Copy strings in C](http://stackoverflow.com/questions/16645583/how-to-copy-char-array-to-another-char-array-in-c) – aslg Oct 07 '15 at 08:40
  • @iharob The compiler will not report excess elements, because you are allowed to drop the null terminator when initializing a character array. See §6.7.9 paragraph 14 in the C11 specification. – user3386109 Oct 07 '15 at 08:50
  • what is your result char array? – ggrr Oct 07 '15 at 09:04
  • You forget the final \0 in all your array `pvtsWsMthDayTab[24]` should be `pvtsWsMthDayTab[25]` `char sDaysInMth[12][2]` `char sDaysInMth[12][3]` – Ôrel Oct 07 '15 at 12:51

1 Answers1

0

You need a char for the final \0, I have used a loop to get the 2 char

#include <string.h> 
#include <stdio.h> 



int main(void) { 
    static char pvtsWsMthDayTab[25]="312831303130313130313031"; 
    char sDaysInMth[12][3] ; 

    memset(sDaysInMth, 0, sizeof(sDaysInMth)); 

    for(int i = 0; i < 12; i++) { 
        for (int j = 0; j < 2; j++ ) { 
            sDaysInMth[i][j] = pvtsWsMthDayTab[i * 2 + j ]; 
        } 
    } 

    for(int i = 0; i < 12; i++) { 
        printf("%s\n",sDaysInMth[i]); 
    } 


    return 0; 
} 
Ôrel
  • 7,044
  • 3
  • 27
  • 46