Search code examples
arrayscpointersmultidimensional-arraychar

why cant i access the location in char pointer array with dereference to int pointer as index


im making a project and i was getting an error out of nowhere supposedly so i went into debug mode and couldn't find the error but the error only occurred in a specific place so i copied the code and ran it and the error repeated. i couldn't search as to why it was giving an error as far as i know this should work. in the code below i tried with direct assigning and it worked but i want to know why the pointer dereference one didn't work.

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

int assign(char**,char*);

int main(){
    char **arr = calloc(9,sizeof(char*));
    char *ele1 = "hello1";

    assign(arr,ele1);
    
    for(int i=0;i<2;i++){
        printf("%s\n",arr[i]);
    }
}

int assign(char **arr,char *ele1){
    for(int *i=0;*i<2;(*i)++){
        arr[*i]=ele1;       
     }
    // for(int i=0;i<2;i++){
    //  arr[i]=ele1;        
    // }
}

i commented the first 3 lines in assign function and uncommented the remaining and tried and it worked. here im only assigning 2 values but that shouldnt give any unknown behaviour


Solution

  • Let's analyze this loop:

    for(int *i=0;*i<2;(*i)++){
        arr[*i]=ele1;       
    }
    

    int *i=0 - i is defined as a pointer to int and initialized to 0 (i.e. it is initialized to a NULL pointer).

    Then you have 3 places where you dereference it (using *i):
    (1) *i<2
    (2) (*i)++
    (3) arr[*i]=ele1;

    But dereferencing a NULL pointer invokes UB (Undefined Behavior).

    But in any case an index into an array should not be a pointer, but rather an integral value like int.
    In the commented out version i in an int (which is perfectly valid as an index into an array), not a pointer to int and initializing it to 0 is exactly what you need.

    A side note:
    assign is declared to return an int, so either return some relevant value, or change it to be a void function.