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



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

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

主要是:

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

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

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

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("%sn", *strptr++); count++;}
//strptr -= count;
//strptr = pointerartihm(strptr, -count);
threestar(&strptr, -count);
printf("nn After the "reset" - %sn", *strptr);
}

https://godbolt.org/z/qbvz9G

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

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

最新更新