Passing Pointer To An Array Of Arrays Through Function

前端 未结 6 1764
南旧
南旧 2021-01-21 14:00

There is a pointer-to-an-Array of Arrays i.e. NameList in the code. I want the contents of each of the Arrays in the Pointer(NameList) to get printed one by one. The below co

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 14:30

    I made some corrections in your program please find them and compare. I know its too late for the response. But I saw this today itself.

    int Data1[] = {10,10};
    int Data2[] = {20,20};
    int Data3[] = {30,30};
    
    int *NameList[] = {Data1, Data2, Data3};
    
    main()
    {  
      Function(NameList); 
    }
    
    Function(int *ArrayPointer)
    { 
        int i, j, index=0;
        for (i=0; i < 3; i++)
          {
            for (j=0; j < 5; j++)
              {
                 //It does not print the data
                 printf("\nName: %d\n", *((int *)ArrayPointer[i] + index));
             index++;
              } 
            index=0;         //Counter reset to 0
          }
      }
    

    Explanation:

    When you pass NameList to Function as a pointer to an integer, what gets passed is the address of the first element of the array, which happens to be Data1 (an address to an array). But since this address is held in an array of ints, it will be considered as an integer. To make it behave like an address to an array(or, for that matter pointer to an int) you need to cast it to (int *). Thats what I did in :

    printf("\nName: %d\n", *((int *)ArrayPointer[i] + index));

提交回复
热议问题