重置c中函数中字符串数组的指针位置

重置c中函数中字符串数组的指针位置,c,function,pointers,C,Function,Pointers,我试图通过使用一个函数在开始时重置指针的位置。我的想法是向函数发送字符串数组的地址。通过减少指针,内存中的指针也应该减少,这样我应该能够在返回主函数时再次从头开始操作指针,但这似乎不起作用,位置保持不变 void reset(char ***g,int count){ for (int i = 0; i < count; i++){ g--; } } 我还假设,使一个函数返回一个位置减少的新指针是无用的,因为我们还不能释

我试图通过使用一个函数在开始时重置指针的位置。我的想法是向函数发送字符串数组的地址。通过减少指针,内存中的指针也应该减少,这样我应该能够在返回主函数时再次从头开始操作指针,但这似乎不起作用,位置保持不变

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

我还假设,使一个函数返回一个位置减少的新指针是无用的,因为我们还不能释放原始指针,它可能在另一个上下文中有用,但在这个上下文中可能不有用。

您不需要在循环中递减。这是一个简单的指针算法。在下面的示例中,您有一些示例

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);
}


你的问题基本上是这样的:

int i = calculate_something();
// doing my operations and incrementing i
// how do I get i back to the number I calculated?
答案是,使用一个单独的变量:

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

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

g--
如何正确
g
reset
功能中的局部变量。也许您需要类似于
*g--
?另外,这是从一个非常快速的概述。这在你的生活中似乎是错误的code@SuraajKS一开始,我也这么想,但它也不以这种方式工作。
//用指针执行操作是个坏主意。最好记住从malloc()得到的指针。如果您需要一个额外的指针(或索引),只需声明另一个指针。我同意@wildplasser。最好使用另一个指针来迭代strings@wildplasser无论我使用多少个别名指针,我都需要在最后释放它们,因为位置不好,其中至少有一个会有相同的问题。我的想法是创建一个循环此过程的函数,因为“for cycle”在主函数中正常工作。您好,感谢您发布解决方案。iI与修改您在这里写的内容相关:它通过释放strepr而不是strings来工作。或者,一旦释放(strings)就没有用了,因为它们指向相同的内存地址吗?@Virgula有很多问题。您没有分配足够的内存。在我的示例中,指针数组必须以NULL结尾才能工作。是的,我没有分配足够的内存,因为我写得很快。不管怎样,我明白了,谢谢你。
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