将指针转换为int并稍后再返回指针是否安全?
如果我们知道指针是否为32位长且int是32位长怎么样?
long* juggle(long* p) {
static_assert(sizeof(long*) == sizeof(int));
int v = reinterpret_cast<int>(p); // or if sizeof(*)==8 choose long here
do_some_math(v); // prevent compiler from optimizing
return reinterpret_cast<long*>(v);
}
int main() {
long* stuff = new long(42);
long* ffuts = juggle(stuff);
std::cout << "Is this always 42? " << *ffuts << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这是否包含在标准中?
void*从内存的角度来看,将整数值转换为或者反之亦然?我的理解是void*一个未指定长度的内存块的地址.
这似乎就像比较苹果和橙子.
int myval = 5;
void* ptr = (void*)myval;
printf("%d",(int)ptr);
Run Code Online (Sandbox Code Playgroud)
我意识到我应该给出使用它的确切上下文.
int main(int argc, char* argv[]) {
long thread; /* Use long in case of a 64-bit system */
pthread_t* thread_handles;
/* Get number of threads from command line */
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]);
thread_handles = malloc (thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], NULL, Hello, (void*) thread); …Run Code Online (Sandbox Code Playgroud) 我想再次选择我的C技能.我想在不同的线程中对一个序列求和,每个线程将返回一个序列的一部分之和的指针.然而,当我试图转换void*类型值local_sum来int,发生了问题.
我试图转换sum += *(int*)local_sum;,发生了一个段错误,我得到了Process finished with exit code 11.
我发现,如果我使用sum += (int)local_sum;,那就没关系.但我无法说服自己:不应该local_sum是一个void *?为什么它可以转换为int用(int)local_sum?
我很感激你能回答这个问题.
将每个进程的返回值相加的部分在这里:
int sum = 0;
for (int i = 0; i < NUM_THREADS; i ++) {
void * local_sum;
pthread_join(count_threads[i], (&local_sum));
sum += (int)local_sum;
}
Run Code Online (Sandbox Code Playgroud)
线程的功能在这里:
void * count_thr(void *arg) {
int terminal = ARRAY_SIZE / NUM_THREADS;
int sum = 0;
for (int i = 0; …Run Code Online (Sandbox Code Playgroud) 首先,这不是一个骗局:
问题的不同之处在于:我只使用void*来存储int,但我实际上从未将它用作void*.
所以这个问题真的归结为:
void*保证至少与int一样宽
我不能使用intptr_t,因为我使用的是c89/ANSI C.
编辑
在C99(gcc版本)的stdint.h中,我看到以下内容:
/* Types for `void *' pointers. */
#if __WORDSIZE == 64
# ifndef __intptr_t_defined
typedef long int intptr_t;
# define __intptr_t_defined
# endif
typedef unsigned long int uintptr_t;
#else
# ifndef __intptr_t_defined
typedef int intptr_t;
# define __intptr_t_defined
# endif
typedef unsigned int uintptr_t;
#endif
Run Code Online (Sandbox Code Playgroud)
我可能只是偷偷摸摸地装上类似的东西并期望它能起作用吗?似乎转换应该工作,因为所有intptr_t都是整数类型的typedef ...