首页 > 解决方案 > C中的这些访问有什么区别?

问题描述

我今天开始学习 C,我有一些关于访问指针数据的问题。

我在C中有这个功能:

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:使用“&”访问它获取内存位置/地址。

当我赋予数组的值时,我只能传递指针,这是为什么呢?我不应该归因于实际价值吗?就像在第二次访问中一样。

当我访问指针时,这个数字是什么?(首次访问)

标签: c

解决方案


因此,在第一个 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 表来查看哪个数值对应于哪个字符。


推荐阅读