0

我正在寻找学习 C 并且很难掌握字符串指针的概念(通常只是指针)。

我有以下程序:

#include<stdio.h>
#include<string.h>

int main()  
{   

    // char test[6] = "hello";
    char *test = "hello"; // test is a pointer to 'h'

    int size_of_test_pt = sizeof(test); // this is the size of a pointer? which is 8 bytes.
    int size_of_test = sizeof(*test); // this is the size of h, which is 1.

    printf("\nSize of pointer to test: %d\n", size_of_test_pt);  // prints 8
    printf("\nSize of test: %d\n", size_of_test);   // prints 1

    printf("\nPrint %s\n", test); // why does this print 'hello', I thought test was a pointer?
    printf("\nPrint %c\n", *test); // this is printing the first character of hello, I thought this would print hello.
    printf("\nPrint %i\n", *test); // this prints 104...is this ASCII for h

    return 0;
}

在最后 3 个打印语句之前,一切都是有意义的。如果 test 是一个指针变量。为什么 printf 打印出单词“hello”而不是地址?

对于printf("\nPrint %c\n", *test)调用是否正确理解我正在取消引用测试,这是一个地址并访问第一个元素,然后将其打印到屏幕上?

4

3 回答 3

2

转换说明符%s旨在输出字符串,它期望作为参数的类型的指针表达式char *const char *指向要输出的字符串的第一个字符。

在这种情况下,函数输出从提供的指针指向的地址开始的所有字符,直到'\0'遇到终止的零字符。

如果要输出此类指针的值,则需要编写

printf("\nPrint %p\n", ( void * )test);

转换说明符%c旨在输出类型的单个对象char

请注意,指针test指向字符串字面量的第一个字符"hello"。因此,取消引用指针,您将获得字符串文字的第一个字符。

这是一个演示程序。

#include <stdio.h>

int main( void )
{
    char *test = "hello";

    for ( ; *test != '\0'; ++test )
    {
        printf( "%c ", *test );
    }

    putchar( '\n' );
}

程序输出为

h e l l o

字符串文字作为包含以下元素的字符数组存储在内存中

{ 'h', 'e', 'l', 'l', 'o', '\0' }
于 2022-01-28T18:00:04.517 回答
0

在 C 中,“字符串”是一系列字符,例如h, e, l, l, o。为了指示序列正在结束,特殊值 0 被附加到序列中。

如果没有指针之类的东西,将字符串传递给函数将涉及复制整个字符序列。这通常是不切实际的,所以我们只是传递一个引用(即指针),告诉在哪里可以找到字符串的第一个字符。

这非常常用,以至于指针本身有时被称为字符串,即使它实际上是指向字符串的指针。字符串本身就是字符序列。

将指针想象为标识特定书籍的参考书目。在文本中包含这样的参考比插入整本书的副本要实用得多。

于 2022-01-28T20:34:21.617 回答
0

如果 test 是一个指针变量。为什么 printf 打印出单词“hello”而不是地址?

简而言之,这是因为%s期望它的参数是 type char *

对于 printf("\nPrint %c\n", *test) 调用是否正确理解我正在取消引用测试,这是一个地址并访问第一个元素,然后将其打印到屏幕上?

是的。格式说明符期望其%c参数为 a char,而这正是您取消引用指向char. 此外,它知道将该值打印为字符。在下面的行中,%i参数需要 type 的值int,并且由于char是 kind of ,它接受它并打印您提供int的字符 ( ) 的数值。h

于 2022-01-28T18:59:55.377 回答