打印一个char指针...会发生什么? [英] printing a char pointer ... what happens?

查看:53
本文介绍了打印一个char指针...会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,我有一个关于char指针以及它将输出什么的问题.看看:

i'm new to C and i've got a question about char pointers and what it will print . take a look :

int main()
{
char *p1="ABCD";
p1="EFG";
printf ("%s",p1);
return 0;
}

它将打印EFG

现在:

int main()
{
char *p1="ABCD";
//p1="EFG";
printf ("%s",p1);
return 0;
}

它将为您提供ABCD

and it will give you ABCD

我不明白的是 * p1 到底是什么?
它是一个包含 char 值的地址的数字吗?它是 char 吗?
现在 * p1 中有什么?为什么是 const ?

The point that I don't get is what exactly *p1 is ?
Is it a number of an address that contains a char value ? Is it a char ?
what is in *p1 right now ? Why is it const ?

推荐答案

从C标准开始:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf

EXAMPLE 8 The declaration

  char s[] = "abc", t[3] = "abc";
  defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals.

This declaration is identical to

  char s[] = { 'a', 'b', 'c', '\0' },
  t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

  char *p = "abc";

defines p with type ‘‘pointer to char’’ and initializes it to point to an object
with type ‘‘array of char’’ with length 4 whose elements are initialized with a
character string literal. If an attempt is made to use p to modify the contents
of the array, the behavior is undefined.

换句话说:

1) char * p1; 声明一个变量(p1),它是一个指针.指针p1可以更改.

1) char *p1; declares a variable (p1) that is a pointer. The pointer, p1 can be changed.

2) char * p1 ="ABCD"; 声明p1(与"1"相同)并初始化其指向的数据(将其初始化为只读的5元素字符数组"ABCD \ 0").

2) char *p1 = "ABCD"; declares p1 (same as "1") and also initializes the data it points to (initializes it to the read-only, 5-lelement character array "ABCD\0").

因此,您可以将地址"p1"更改为指向的地址(可以使其指向"EFG",将其分配为NULL等).但是您不能安全地更改数据本身.如果您尝试覆盖"ABCD",则可能会遇到访问冲突".确切的行为是未定义"-任何事情都可能发生.

So you can change the address "p1" points to (you can make it point to "EFG", assign it to NULL, etc. etc). But you CANNOT safely change the data itself. You'll probably get an "access violation" if you try to overwrite "ABCD". The exact behavior is "undefined" - ANYTHING can happen.

3) char p2 [] ="ABCD"; 声明一个变量(p2),它是一个数组.它分配5个字符,并将数据初始化为"ABCD \ 0".

3) char p2[] = "ABCD"; declares a variable (p2) that is an array. It allocates 5 characters, and initializes the data to "ABCD\0".

该数组是可读写的(可以更改数组中的数据),但是不能更改变量"p2"(不能将p2更改为指向另一个地址-因为它不是指针).

The array is read-write (you can change the data in the array), but the variable "p2" cannot be changed (you cannot change p2 to point to a different address - because it's not a pointer).

4)那么char *指针和char数组[]之间的区别"是什么?这是一个很好的讨论:

4) So what's the "difference" between a char *pointer and a char array[]? Here is a good discussion:

http://c-faq.com/aryptr/aryptrequiv.html

这篇关于打印一个char指针...会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆