strcat 查询(string.h)
首先: STRCAT :
当定义清楚地表明:
char * strcat ( char * destination, const char * source );
为什么他们在示例中使用 char str[80] ??? 他们不应该使用字符指针吗?
First off :
STRCAT :
When clearly the definition says :
char * strcat ( char * destination, const char * source );
Why'd they use char str[80] in the example???
Shouldn't they have used a character pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为在 C/C++ 中数组会退化为指针。如果定义
char s[80]
s 的值将是第一个字符的地址,即&s[0]
That is because arrays decay into pointers in C/C++. If you define
char s[80]
the value of s will be the address of the first character i.e&s[0]
数组也可以用作指针。 strcat 需要的是指向复制目标字符串的内存的指针。在本例中,
str[80]
将为您提供可容纳 80 个字符的内存。array can also be used as pointer. what
strcat
needs is the pointer to a memory in which it copies the destination string. In this casestr[80]
will give you the memory that can hold 80 chars.声明一个 80 个字符的数组。
但是,在 C 和 C++ 中,数组会隐式转换为指针。当您将数组传递给函数(例如 strcat)时,它会自动“衰减”,形成指向数组第一个元素的指针。
这并不等于说数组和指针是同一件事。他们不是。例如,
sizeof()
对上述数组和char*
产生不同的结果。declares an array of 80 characters.
However, in C and C++, arrays are implicitly converted to pointers. When you pass an array to a function (such as strcat), it automatically "decays", forming a pointer to the first element of the array.
That's not the same as saying that arrays and pointers are the same thing. They aren't. For example,
sizeof()
yields different results on the above array, and achar*
.严格来说,数组是指向内存块开头的指针。所以
str
是一个char *
,它指向 80 个字符的开头。当您对数组进行索引时,例如位置 53,以下内容是等效的:
str[53]
与*(str + 53)
相同,因为 str 只是一个 < code>char * 并将 53 添加到字符指针将返回一个指针,因此要获取内部的值,您必须使用星号来取消引用该指针。实际上,数组表示法只是使代码在某些情况下更具可读性。实际上,当您在复制字符串时想要跳过一些前导文本时,字符数组的一个很棒的小技巧是。例如,假设您的数组
str[80]
包含字符串“1023:代码错误!”
。并且您只想显示字符串而不显示前面的数字。在这种情况下,您可以说printf( "%s", str + 6 )
并且只会打印"error in code!"
。An array is, strictly speaking, a pointer to the beginning of a block of memory. So
str
is achar *
that points to the beginning of 80 characters.When you index into an array, say position 53, the following is equivalent:
str[53]
is the same as*(str + 53)
as str is just achar *
and adding 53 to a character pointer will return a pointer so to get the value inside you have to use an asterisk to dereference the pointer. In effect array notation just makes code more readable in certain circumstances.Actually a great little trick with arrays of char is when you want to skip over some leading text when copying a string. E.g. let's say your array
str[80]
contains the string"1023: error in code!"
. And you want to display just the string without the number in front. In this case you could sayprintf( "%s", str + 6 )
and only"error in code!"
would be printed.编辑:
哦,我匆忙回答。正如dribeas所说,该语句声明了一个数组,并且str在使用时可以隐式转换为指针。例如:
是无效操作,而:
则不是。
Edit:
Opps, I rushed my answer. As dribeas says the statement declares an array and str can be implicitly converted into a pointer when it is used. For instance:
is an invalid operation while:
isn't.