Array of pointers to arrays

前端 未结 4 1896
温柔的废话
温柔的废话 2021-01-05 03:47

I am new to C programming and this is my problem:

I want to store the first value of each array in a new array, then the second value of each array in a new array an

4条回答
  •  走了就别回头了
    2021-01-05 04:04

    You have stored the data as you intended, you just need to access it properly

    for (i=0; i<4;i++)
    {
      for (j = 0; j < 4; j++) {
        int* temp = tab[i];    
        printf("%d\t", temp[j]);      // or try the next line...
        printf("%d\t", *(temp + j));  // prints same value as above line
        printf("%d\t", tab[i][j];     // the same value printed again
      }
    }   
    

    All of the above print the same value, it is just different ways of accessing that value using pointer arithmetic. Each element of tab is a int* the value of each is the address of your other defined int[] arrays at the start

    Edit: In response to the comment of Jerome, you can achieve that by declaring 4 arrays

    int tab1[4]={*t1,*t2,*t3,*t4};
    int tab2[4]={*(t1+1),*(t2+1),*(t3+1),*(t4+1)};
    int tab3[4]={*(t1+2),*(t2+2),*(t3+2),*(t4+2)};
    int tab4[4]={*(t1+3),*(t2+3),*(t3+3),*(t4+3)};
    

    Now tab1 contains the first elements of each array, tab2 the second elements, and so on. Then you can use

     int *tttt[4]={tab1,tab2,tab3,tab4};
     for (i=0; i<4;i++) {
       for (j = 0; j < 4; j++) {
         printf("%d\t", tttt[i][j]);   
       }
     } 
    

    to print what you wanted. If you declared another pointer array like you did at the start

      int* tab[4] = {t1,t2,t3,t4};
    

    then essentially in matrix terms, tttt is the transpose of tab

提交回复
热议问题