Sog*_*ogo 4 c unix porting casting
当我调试我的次要移植程序时,我对类型转换差异有疑问.
这是我的来源(下面):
1 #include <time.h>
2 #include <stdio.h>
3
7 int main () {
8 clock_t now; //unsigned long
9 struct tm * mac_time; // const long
10 char *time_str;
11 now = time (NULL);
12 mac_time = localtime((const long *)&now);
13 // localtime ( const long <- unsigned long)
13 time_str = asctime(mac_time);
14 printf("Now : %s\n",time_str);
15 return 0;
16 }
Run Code Online (Sandbox Code Playgroud)
首先,它正常工作,现在没有错误.但我对类型铸造差异有疑问.
在第12行中,由于发生了类型转换警告,我更改了调试的值类型.
但有什么区别
12 mac_time = localtime((const long *)&now);
Run Code Online (Sandbox Code Playgroud)
和
12 mac_time = localtime(&(const long *)now);
Run Code Online (Sandbox Code Playgroud)
我认为彼此之间没有区别,因为这只是'铸造价值的地址和'价值的地址铸造'.
但是,后者抛出了警告信息.
你会就这种铸造问题给我一些建议吗?
(const long *)&now获取地址now并将其解释为a的地址const long.
&(const long *)now解释now为a的地址const long并获取该地址的地址.这很危险,因为您基本上将整数或浮点数转换为指针,而没有任何理由说明为什么now应用程序可以访问标识的内存位置.