【问题标题】:Problem with storing value in pointer address在指针地址中存储值的问题
【发布时间】:2022-01-11 12:05:03
【问题描述】:

我设法在函数中将值放入指针中,但是当我回到主函数时,我只是没有得到值。我哪里错了?发送参数错误?分配错误?代码如下:

bool wc(int* nlines, int* nwords, int* nchars)
{
    int lines=5,chars=6,words=7;
    nchars = (int *) malloc(chars*sizeof(int));
    *nchars = chars;
    nlines = (int *) malloc(lines*sizeof(int));
    *nlines = lines;
    nwords = (int *) malloc(words*sizeof(int));
    *nwords = words;

}
int main() {
    int* chars; int* words; int* lines;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",chars,lines,words);
    return 0;
}

【问题讨论】:

  • C and pointer in a function - changes do not save 不太清楚您为什么要为此使用malloc。您只是在每个参数中存储一个值,并且假设lineswordschars 被声明为int,它们已经为此指向空间。如果您删除 malloc 行,它应该可以正常工作。如果这是minimal reproducible example,我们肯定会知道。
  • @RetiredNinja 我不知道是什么问题,所以我只是分配了。我也试过不这样做。顺便说一句,我没有返回指针的选项,不确定你链接的内容是否对我有帮助。
  • 在wc中,nlines,nwords,nchar是用main()的一些变量的地址初始化的局部变量,它们的内容被动态缓冲区的地址替换(在wc中用malloc本地),那么你写入这些动态缓冲区(因此不在主变量中)。所以高层变量是不变的。
  • 值得注意的是,你的函数说它会返回一个值,但它没有。这会导致未定义的行为。
  • @RetiredNinja 是的,我没有添加我返回 true 的那部分,因为它与我的问题无关。

标签: c pointers


【解决方案1】:

如果您只想在一个函数中设置 3 个 int 值,那么我就是这样做的。

#include <stdio.h>
#include <stdbool.h>
 
bool wc(int* nlines, int* nwords, int* nchars)
{
    int lines=5,chars=6,words=7;
    *nchars = chars;
    *nlines = lines;
    *nwords = words;
    return true;
}
int main() {
    int lines = 0;
    int words = 0;
    int chars = 0;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",chars,lines,words);
    return 0;
}

如果由于某种原因您必须使用示例中所示的指针,那么这将满足您的需求。

#include <stdio.h>
#include <stdbool.h>
 
bool wc(int** nlines, int** nwords, int** nchars)
{
    int lines=5,chars=6,words=7;
    *nchars = malloc(sizeof(int));
    **nchars = chars;
    *nlines = malloc(sizeof(int));
    **nlines = lines;
    *nwords = malloc(sizeof(int));
    **nwords = words;
    return true;
}
int main() {
    int* chars; int* words; int* lines;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",*chars,*lines,*words);
    free(chars);
    free(words);
    free(lines);
    return 0;
}

如您所见,这意味着您需要在各处添加更多 *

【讨论】:

  • 谢谢,我想我终于设法使它工作,即使 mallocing 导致 sigmentation 的 nwords 无缘无故地失败。
【解决方案2】:

在 C 函数中,输入变量是按值传递的,而不是按引用传递的。因此,当您在本地分配它们时,调用者范围内的值不受影响。例如

void foo(int a) {
  a = 5;
}

int main() {
  int b = 3;
  foo(b);
  // here, b is still 3
}

这正是您在示例中所做的,尽管您的变量不是int,而是int*

如果您的输入变量是一个指针,您可以更改变量指向的内存,这显然会反映在调用范围中。例如

void foo(int *a) {
  *a = 5;
}

int main() {
  int b = 3;
  foo(&b);
  // here, b is 5
}

在您的情况下,您想要分配指针,因此您希望函数签名成为指向指针的指针。例如

void foo(int **a) {
  *a = malloc(sizeof(int));
}

int main() {
  int* b = NULL;
  foo(&b);
  // here, b is allocated to a valid heap area
  free(b);
}

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多