【问题标题】:Reset pointer position of an array of strings within a function in c在c中的函数内重置字符串数组的指针位置
【发布时间】:2020-07-20 10:19:33
【问题描述】:

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

    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

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

【问题讨论】:

  • g-- 的正确性如何? greset 函数中的局部变量。也许您需要*g-- 之类的东西?附言这是来自一个非常快速的概述。这在您的代码中似乎是错误的
  • @SuraajKS 一开始我也是这么想的,但是这样也行不通
  • //doing my operations with the pointer 是个坏主意。最好只记住你得到 ftom malloc() 的指针。如果您需要一个额外的指针(或索引),只需声明另一个指针。
  • 我同意@wildplasser。最好使用另一个指针来迭代字符串数组
  • @wildplasser 无论我使用多少个别名指针,我都需要在最后释放它们,并且由于位置不好,其中至少有一个会遇到同样的问题。我的想法是创建一个函数来循环这个过程,因为“for循环”在主函数中正常工作。

标签: c function pointers


【解决方案1】:

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

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

【讨论】:

  • 您好,感谢您发布您的解决方案。我与调整你在这里写的内容有关:godbolt.org/z/YGrz8s 它通过释放 strptr 而不是字符串来工作
  • 或者是因为它们指向同一个内存地址,所以释放(字符串)一旦释放(strptr)就没有用了吗?
  • @Virgula 有很多问题。您没有分配足够的内存。在我的示例中,指针数组必须以 NULL 终止才能工作。 godbolt.org/z/86xoxr
  • 是的,我没有分配足够的内存,因为我写得很快。无论如何,我明白了,谢谢。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多