我設法在函式中將值放入指標中,但是當我回到 main 時,我只是沒有得到值。我哪里錯了?發送引數錯誤?分配錯誤?這是代碼:
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;
}
uj5u.com熱心網友回復:
如果您想要做的就是能夠int在函式內設定 3 個值,那么這就是我想要的。
#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;
}
正如你所看到的,這只是意味著你需要*在整個地方添加更多。
uj5u.com熱心網友回復:
在 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/375254.html
下一篇:對一組指標使用std::less
