[爆卦]man 3 printf意思是什麼?優點缺點精華區懶人包

為什麼這篇man 3 printf意思鄉民發文收入到精華區:因為在man 3 printf意思這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者wtchen (沒有存在感的人)看板C_and_CPP標題[問題] 這段三元運算子的意思是?時間...


開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Linux + gcc5.2.1

額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)


問題(Question):
看到一個面試題目:
typedef int* TYPE;
int f(TYPE x) ;
//Allocate an array of two integers;
//return 0 if the allocation succeeded, 1 otherwise.
//Return the allocated array in x
int f(TYPE x) {
int* ret = (int*) malloc(sizeof(int[2]));
return ret ? *x=ret, 0:1 ; //-> 這行不懂
}

TYPE 該怎麼定義?
我試過只有typedef int* TYPE 可以編譯過
可是我不懂最後一行
一般來說三元運算子不是

val = x ? y : z ;

等於
if(x == true) val = y;
else val = z;

可是函式這行我不懂...
餵入的資料(Input):


預期的正確結果(Expected Output):


錯誤結果(Wrong Output):


程式碼(Code):(請善用置底文網頁, 記得排版)
以下是我的測試程式:
#include <stdio.h>
#include <stdlib.h>

typedef int* TYPE;
int f(TYPE x) {
int* ret = (int*) malloc(sizeof(int[2]));
return ret ? *x=ret, 0:1 ;
}

int main(void) {
TYPE a;
printf("%d\n", f(a));
return 0;
}



補充說明(Supplement):
編譯結果(gcc Q_15.c -Wall):
Q_15.c: In function ‘f’:
Q_15.c:7:20: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
return ret ? *x=ret, 0:1 ;
^
Q_15.c: In function ‘main’:
Q_15.c:12:5: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
printf("%d\n", f(a));
^

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.112.247
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1448643722.A.577.html
※ 編輯: wtchen (90.41.112.247), 11/28/2015 01:11:09
legendmtg: operator, 會把整串敘述作完 然後回傳最右邊的那個值 11/28 01:36
legendmtg: 他只是在return 0之前多塞了*x=ret進去而已 11/28 01:38
wtchen: 所以這邊一樣先判斷ret是true or false,然後不管判斷 11/28 02:48
wtchen: 結果如何都執行*x=ret? 11/28 02:49
wtchen: 然後ret==true時 ret=0,反之則ret=1? 11/28 02:50
uranusjr: ? : 中間的東西會自動成為一組, 所以只有在 ret 為真時 11/28 06:03
uranusjr: 才會發生 assignment, 其他就和你理解的一樣 11/28 06:03
uranusjr: if (ret) { *x = ret; return 0; } else { return 1; } 11/28 06:04
wtchen: 了解,感謝! 11/28 18:21
Killercat: 其實你把*x=ret前後加個()應該就懂了 11/29 21:57
Killercat: 跟某些for迴圈的trick一樣的做法 11/29 21:57
james732: 話說這個f應該要改成 int f(TYPE *x) 才對? 11/30 22:27
james732: http://ideone.com/nlC5fC 整個程式改成這樣 11/30 22:30
wtchen: 不懂為何要改int f(TYPE *x) (該程式是照抄面試題) 12/03 00:29
LPH66: 它是藉 x "回傳"一個 TYPE 型態變數, 當然要 TYPE*... 12/03 01:14

你可能也想看看

搜尋相關網站