![](/img/trans.png)
[英]How to cast a C void* pointer to a pointer to a struct (with definition of the struct as a string)?
[英]How to cast a pointer to void which is nested in a struct?
本示例是為演示而准備的,但我需要像示例中那樣強制轉換指針
我收到以下錯誤:
test2.c: In function ‘main’:
test2.c:25:12: error: expected identifier before ‘(’ token
test2.c:25:12: error: too few arguments to function ‘strcpy’
test2.c:26:20: error: expected identifier before ‘(’ token
代碼是這樣的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
void *ptr;
char str[300];
};
struct test2 {
int i;
char astr[200];
};
int main(void)
{
struct test *p;
p = malloc(sizeof(struct test));
p->ptr = malloc(sizeof(struct test2));
/*
void *p2;
p2 = p->ptr;
strcpy(((struct test2 *)p2)->astr, "hello world");
printf("%s\n", ((struct test2 *)p2)->astr);
*/
strcpy(p->(struct test2 *)ptr->astr, "hello world");
printf("%s\n", p->(struct test2 *)ptr->astr);
return 0;
}
該代碼的注釋掉部分效果很好。 我知道處理器不能在沒有其他變量的情況下取消對指針的引用,並且編譯器將創建一個附加變量,但是我想了解如何在不創建其他變量的情況下轉換嵌套在結構中的指針?
為了使代碼看起來更緊湊,我經常會使用類似的東西,並且我希望將其寫成一行而沒有其他變量。
C ++變體:
strcpy(reinterpret_cast<struct test2 *>(p->ptr)->astr, "hello world");
還值得指出的是, strcpy
函數是不安全的,不應使用。 請改用strcpy_s
。
您需要將->
應用於轉換結果(注意整個轉換表達式周圍的括號):
strcpy(((struct test2 *)(p->ptr))->astr, "hello world");
printf("%s\n", ((struct test2 *)(p->ptr))->astr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.