Virgula
Virgula

Reputation: 348

Reset pointer position of an array of strings within a function in c

I'm trying to reset the position of a pointer at the beginning by using a function. My idea was to send to the function the address of the array of strings. By decrementing the pointer it should also be decreased in memory so I should be able again to manipulate my pointer from the beginning once getting back in my main function, but this seems not working and the position remains unaltered.

    void reset(char ***g,int count){
        for (int i = 0; i < count; i++){
          g--;
        }
    }

and in the main:

char **array_of_strings = malloc etc....
//doing my operations and incrementing the pointer position
reset(&array_of_strings,count); //where count is how many time position of array_of_strings has been incremented 
free(array_of_strings); //invalid pointer position

I also assume that making a function which returns a new pointer with the decreased position it's useless because we are not able to free the original pointer yet, it could be useful in another context maybe but not in this one.

Upvotes: 0

Views: 790

Answers (2)

Your question is basically like this:

int i = calculate_something();
// doing my operations and incrementing i
// how do I get i back to the number I calculated?

And the answer is, you use a separate variable:

int i = calculate_something();
int j = i;
// doing my operations and incrementing j
// now i still has the original number

With pointers:

char **array_of_strings = malloc etc....
char **temp_pointer_to_array_of_strings = array_of_strings;
// doing my operations and incrementing the pointer position of the second one
// now array_of_strings still has the original pointer
free(array_of_strings); // valid

Upvotes: 0

0___________
0___________

Reputation: 67820

You do not need to decrement in a loop. It is simple pointer arithmetic. In the example below you have some examples

char *strings[] = {"111","222","3333","4444", "555", NULL};

char **strptr = strings;

char ** pointerartihm(char **ptr, ssize_t count)
{
    return ptr + count;
}

char **threestar(char ***ptr, ssize_t count)
{
    *ptr += count;
    return *ptr;
}

int main(void)
{
    ssize_t count = 0;
    while(*strptr) {printf("%s\n", *strptr++); count++;}

    //strptr -= count;
    //strptr = pointerartihm(strptr, -count);
    threestar(&strptr, -count);

    printf("\n\n After the \"reset\" - %s\n", *strptr);
}

https://godbolt.org/z/qbvz9G

Upvotes: 1

Related Questions