繁体   English   中英

在 c 中使用指针操作字符数组

[英]Manipulating char arrays using pointers in c

所以我尝试了这段代码

#include <stdio.h>
int main(void)
 {
        char string[] = "hello world";
        char *my_ptr = string;
        *my_ptr='Y';
        printf("the first char of string is %c", *my_ptr);
 }

输出_1 :-

the first char of string is Y

现在,如果我想在字符串(“黄色世界”)中打印完整的气味。 为此,我将第 7 行更改为:-

printf("the whole string is %s", *my_ptr);

输出_2:-

Segmentation fault (core dumped)

但是,如果我尝试将其更改为:-

printf("the whole string is %s", my_ptr);

输出_3 :-

the whole string is Yello world
  1. 有人可以解释一下为什么第二种情况失败了吗?

  2. 为什么第三种情况打印正确?

根据我的理解 *my_ptr (以及 my_ptr 两者)都有第一个位置的地址,那么为什么第一个无法打印完整的 string ,而第二个却做得很好。 我是初学者,所以如果您能详细说明这些情况下这种行为背后的原因,将会有所帮助。

my_ptrchar *类型,它是字符串第一个字符上的指针。

*my_ptrchar类型,它是一个字符。

printf格式字符串选项%s接受一个char * ,它将遍历每个字符,直到找到一个字符串分隔符 (0) :

首先, *my_ptr ,是 Y

然后*(my_ptr + 1) ,是 h

等等...

当用printf与*my_ptr的内容为*my_ptr将传递给printf的,如果它是一个字符串指针。 它的值为 'Y',ASCII 格式为 89。

printf 将尝试访问地址 89 处的指针,认为它是一个有效的字符串指针,但该地址很可能不可读,内核将终止尝试访问它无法访问的内存的程序。

这将起作用:

#include <stdio.h>
int main(void)
 {
        char string[] = "hello world";
        char *my_ptr = string;
        *my_ptr='Y';
        printf("the first char of string is %c", *my_ptr);
        printf("the whole string is %s", my_ptr);
 }

my_ptr是指向整个字符串的指针。 *my_ptr是字符串开头的字符值。

printf("%s", char*)
printf("%c", char)

这个:

printf("the whole string is %s", *my_ptr);

取消引用该指针,因此它将char类型的值传递给printf() ,然后它会将它(由于%s格式说明符)解释为const char * ,即作为指向只读字符数据的指针。 指针的值是内存中存储某些数据的位置的地址。

这将使printf()从一些非常低的地址开始读取字符,您的程序可能不允许读取该地址。 因此出现分段错误。

在下面的声明中:

     printf("the whole string is %s", *my_ptr);

它将从 *my_ptr 的地址读取内容。 这会产生分段错误(核心转储)而在下面:

     printf("the whole string is %s", my_ptr);

该字符串将从 string[] 的基地址读取。 要读取字符串,您必须从字符开始读取的位置传递基地址,直到找到 '\\0' 字符。

原因是在 C 中,%s 用于打印字符串,但 u 使用它来打印导致核心转储的字符。

而在C中,给出基地址就足以打印全部内容,无需使用*addr.

如果你想访问一个特定的字符,你可以通过*(a+0)来打印第一个字符和 * (a+1)来打印第二个字符等等。

暂无
暂无

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

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