如果我有代碼:
typedef struct s_ {
int a;
char* b;
} s;
int main()
{
s* st = malloc(sizeof(s));
st->b = malloc(20*sizeof(char));
st->a = 1;
st->b = "foo";
}
是否可以使用偏移量訪問 char 陣列中的資料?例如這里的偏移量是 4 個位元組,我知道并且可以使用例如 offsetof() 宏進行計算,但我無法使用指標演算法訪問資料,例如:
printf("%s", (char*)(st 4));
如果有人可以在這里提供幫助,我會很高興:)
uj5u.com熱心網友回復:
答案可能令人驚訝:st 4實際上將指標增加了 32 個位元組!
這是因為該型別st是struct s_ *,當你添加4到,它是由結構的大小的4倍遞增。
為了移動 4 個位元組,您需要char*先將指標轉換為指標,然后再遞增它。
試試這個: printf("%s", *(char**)((char*)st 4));
編輯:添加*(char**).
之所以需要它,是因為通過遞增指標,我們沒有得到字串的開頭,而是得到指向字串開頭的指標的地址。所以我們需要將它轉換為正確的型別并取消參考它。
uj5u.com熱心網友回復:
您可以使用;計算char *元素的位元組地址b(這是一個char **值)(char *)st offsetof(s, b)因此您可以使用如下代碼訪問字串:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s_
{
int a;
char *b;
} s;
int main(void)
{
s *st = malloc(sizeof(s));
st->b = malloc(20 * sizeof(char));
st->a = 1;
strcpy(st->b, "foo");
char *str = *(char **)((char *)st offsetof(s, b));
printf("[%s]\n", str);
return 0;
}
輸出是包含[foo].
現在你知道為什么你不想這樣做了——讓編譯器為你解決它:
printf("[%s]\n", st->b);
這個問題越來越接近Is it possible to dynamic define a structin C?
uj5u.com熱心網友回復:
如果使用printf("%s", (char*)(st 4));,result 已經偏移 4*struct s
你想列印第四個字符,可以這樣寫
char *ptr = null;
ptr = st;
printf("[%s]",ptr);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406179.html
標籤:
上一篇:添加到結構指標鏈表的尾部
下一篇:關于c中的自由函式
