Array of pointers to arrays

前端 未结 4 1901
温柔的废话
温柔的废话 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 03:59

    Your terminology is a little bit all over the place. I think the easiest way to answer your question is to go through your code line by line.

    int main()
    {
    int t1[4]={0,1,2,3};      //Declares a 4 integer array "0,1,2,3"
    int t2[4]={4,5,6,7};      //Declares a 4 integer array "4,5,6,7"
    int t3[4]={8,9,10,11};    //Declares a 4 integer array "8,9,10,11"
    int t4[4]={12,13,14,15};  //Declares a 4 integer array "12,13,14,15"
    int *tab[4]={t1,t2,t3,t4};//Declares a 4 pointer of integers array "address of the first element of t1, address of the first element of t2, ..."
    int i,j,k,l;              //Declares 4 integer variables: i,j,k,l
    for (i=0; i<4;i++)
     {
      printf("%d\t", *tab[i]); //print out the integer that is pointed to by the i-th pointer in the tab array (i.e. t1[0], t2[0], t3[0], t4[0])
     }
    
     return 0;
     }
    

    Everything you are doing seems ok until your loop. You are showing only the first integer of every array because you are not going through them. To iterate over them, your code should look like this:

    for (i=0; i<4;i++)
    {
       for (j=0; j<4; j++)
       {
          printf("%d\t", *(tab[j] + i));
       }
    }
    

    The above code uses two loop counters, one (the i) to go through the positions in the array (first value in the array, second value in the array, etc.); the other to go through the different arrays (the j). It does this by retrieving the pointer stored in tab[j] and creating a new pointer that has the right offset to show the value for the ith column. This is called pointer arithmetic (there is additional information about pointer arithmetic here)

    Most people find the syntax *(tab[j] + i) to be clunky, but it is more descriptive of what is actually happening. In C, you can rewrite it as tab[j][i], which is much more usual.

提交回复
热议问题