Home > Enterprise >  Creating a variable array of pointers
Creating a variable array of pointers

Time:08-20

I have this piece of code from a program i am writing that doesn't work if i add a condition. All the values are conveniently put based on those the original program would have. I want to create an array of pointers:

    #include <stdio.h>

    int main() {

        int *array2Ptr[3];
        int array2[3][5] = {{4,4,5,5,8},{2,8,2,3,6},{8,8,6,6,1}};
        
        for ( size_t i = 0 ; i < 3 ;   i) {
             array2Ptr[i] = &array2[i][4];
        }
    
         for (size_t i = 0 ; i < 3 ;   i) {  
             printf("%d  ", *array2Ptr[i]);   
         }
      }

No problem here, it works fine.

Now, suppose i want array2Ptr to contain its element based on another array:

    int array1[3] = {3,0,3};
    int array2[3][5] = {{4,4,5,5,8},{2,8,2,3,6},{8,8,6,6,1}};
    int *array2Ptr[2];    //Has size 2 because it should only store 2 values

    for ( size_t i = 0 ; i < 2 ;   i) {

        if ( array1[i] != 0 ) {
           array2Ptr[i] = &array2[i][4];
        }
     }
    
     for (size_t i = 0 ; i < 2 ;   i) {  
         printf("%d  ", *array2Ptr[i]);   
    
     }
   }

This way i get a segmentation fault, why is that?

CodePudding user response:

array2Ptr has size 2, but you are writing array2Ptr[i] for i=2 (3rd item). Edit: In your updated/edited version, you are trying to print array2Ptr[i] when i=2, which was never set to anything (array1[i] != 0 was false).

You need a separate counter for that array.

You could consider something like:

for ( size_t i = 0, j = 0; i < 3 ;   i) {
 if ( array1[i] != 0 ) {
  array2Ptr[j] = &array2[i][4];
  j  ;
 }
}

That way, you only increment the iterator j for array2Ptr when it is used, but still use i as you currently are for the other arrays.

You might want to track that j outside the scope of the loop, so you know how many values to try printing.

CodePudding user response:

It's a better idea to use another iterator like j but if you want to do this with only one iterator, here's a simple solution for that particular code:

for (i = 0 ; i < 2 ;   i) {

    if ( array1[i] != 0 ) {
        array2Ptr[i] = &array2[i][4];
    }
    else {
        array2Ptr[i] = &array2[i 1][4];
    }
 }
  • Related