[英]What makes the difference between direct and indirect access to volatile objects in C?
[英]What is the difference between these access in C?
今天開始學習C,對訪問一個指針數據有一些疑問。
我在 C 中有這個 function:
typedef struct
{
size_t size;
size_t usedSize;
char *array;
} charList;
void addToCharList(charList *list, char *data)
{
if(list->usedSize == list->size)
{
list->size *= 2;
list->array = realloc(list->array, list->size * sizeof(int));
}
list->array[list->usedSize++] = *data;
printf("1: %d\n", *data);
printf("2: %s\n", data);
printf("3: %p\n", &data);
}
我用它來創建一個“自動增長”的字符數組,它有效,但我不明白為什么我需要將值“*data”歸因於我的數組。 我做了一些測試,打印了我嘗試訪問變量“data”的不同方式,我得到了這個輸出(我用字符串“test”測試了它):
1: 116
2: test
3: 0x7fff0e0baac0
1:訪問指針(我認為是指針)給了我一個數字,我不知道是什么。
2:只要訪問變量就可以得到字符串的實際值。
3:使用“&”訪問它會得到 memory 位置/地址。
當我為我的數組賦值時,我只能傳遞指針,這是為什么? 我不應該歸因於實際價值嗎? 就像在第二次訪問中一樣。
當我訪問指針時,這個數字是多少? (第一次訪問)
因此,在第一個 printf 中,您實際上並沒有訪問指針。 如果你有一個名為myPointer
的指針,寫*myPointer
實際上會讓你訪問指針指向的東西。 對此感到困惑是可以理解的,因為在聲明變量時確實使用*
運算符來指定它是指針。
char* myCharPtr; // Here, the '*' means that myCharPtr is a pointer.
// Here, the '*' means that you are accessing the value that myCharPtr points to.
printf("%c\n", *myCharPtr);
在第二個 printf 中,您正在訪問指針本身。 在第三個 printf 中,您正在訪問指向char 指針的指針。 &
運算符放在變量之前時,將返回指向該變量的指針。 所以...
char myChar = 'c';
// pointerToMyChar points to myChar.
char* pointerToMyChar = &myChar;
// pointerToPointerToMyChar points to a pointer that is pointing at myChar.
char** pointerToPointerToMyChar = &pointerToMyChar;
當您嘗試將值存儲在數組中時,它會迫使您執行*data
因為數組存儲字符,而data
是指向字符的指針。 因此,您需要訪問指針指向的 char 值。 你通過*data
做到這一點。
最后: printf("1: %d\n", *data);
的原因打印數字是字符是秘密(或非秘密)數字。 每個字符在幕后都有一個相應的數值。 您可以通過查看ascii 表來了解哪個數值對應於哪個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.