简体   繁体   English

C取消指向字符数组的指针

[英]C derenferencing pointer to character array

I'm trying to grasp C pointers with this small example I found in a tutorial: 我试图通过在教程中找到的这个小例子来掌握C指针:

#include <stdio.h>

int main() {
    char vowels[] = {'A', 'E', 'I', 'O', 'U'};
    char *pvowels = &vowels;

    printf(pvowels);
//  printf(*pvowels);
    return 0;
}

If I compile this I get a warning "Initialization from incompatable pointer type" but it will still compile/run, printing AEIOU plus some random junk characters. 如果我对此进行编译,则会收到警告“来自不兼容指针类型的初始化”,但它仍将编译/运行,并打印AEIOU和一些随机的垃圾字符。 I was also under the assumption that *pvowels would be the character at the first memory location of the vowels array and hence print an 'A' but it just segfaults instead. 我还假设* pvowels将是元音数组的第一个内存位置的字符,因此会打印一个“ A”,但它只会出现段错误。

My two questions are: 我的两个问题是:

Why does the 1st printf print out the vowels + junk? 为什么第一个printf打印出元音+垃圾?

Why does the 2nd print not print out just an A? 为什么第二张打印纸不能仅打印出一个A?

When you use &vowels you get a pointer to the array not the first element in the array. 使用&vowels您将获得指向数组的指针,而不是数组中的第一个元素。 The type of &vowels is char(*)[5] . &vowels的类型为char(*)[5]

To fix this problem you should either use &vowels[0] to get a pointer to the first element, or rely on that arrays naturally decays to pointers to their first element: 要解决此问题,您应该使用&vowels[0]获取指向第一个元素的指针,或者依靠该数组自然衰减到指向其第一个元素的指针:

char *pvowels = vowels;

The second problem is that you treat pvowels like a string , but a string is a sequence of characters with a terminator . 第二个问题是您将pvowels 字符串 ,但是字符串是带有终止符的字符序列。 Since the array vowels doesn't have this terminator the printf call will go out of bounds and you will have undefined behavior . 由于数组vowels没有终结符,所以printf调用会越界,您的行为不确定

As for the last problem, when you dereference a pointer you get the value of the location where it points. 至于最后一个问题,当取消引用指针时,将获得它所指向的位置的值。 Because the location of the array starts with the first element of the array both &vowels[0] and &vowels points to the same location, so when you dereference pvowels you get the first element of the array which is the character 'A' . 因为数组的位置从数组的第一个元素开始,所以&vowels[0]&vowels指向相同的位置,因此,当取消引用pvowels将得到数组的第一个元素'A' However you can't use it as the first argument for printf because the printf function expects it to be a string (a pointer to a zero-terminated array of characters), not a single character. 但是,您不能将其用作printf的第一个参数,因为printf函数希望它是一个字符串 (指向以零结尾的字符数组的指针),而不是单个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM