我有以下代碼:C:訪問從一個指針的函數外
int takeEven(int *nums, int numelements, int *newlist) {
newlist = malloc(numelements * sizeof *newlist);
int i, found = 0;
for(i = 0; i < numelements; ++i, nums++) {
if (!(*nums % 2)) {
*(newlist++) = *nums;
found++;
}
}
newlist -= found;
printf("First number found %d\n", *newlist); // <= works correctly
return found;
}
int main()
{
int nums[] = {1,2,3,4,5};
int *evenNums;
int i;
int n = takeEven(nums, sizeof(nums)/sizeof(*nums), evenNums);
for (i = 0; i < n; ++i) {
printf("%d\n", *(evenNums++));
}
return 0;
}
上述代碼的輸出:
-1
2088999640
2088857728
如果我嘗試打印的第一個元素newlist
指針在返回函數(printf("First number found %d\n", *newlist);
)之前,它按預期工作,但爲什麼當我嘗試從函數的外部訪問指針時,我從表面上看不到這些值地址?
呵呵,條件需要是'(!(* nums%2))';我現在解決了這個問題 – 2009-11-17 10:38:14