Ç - 为什么它是有意义的索引字符指针是一个int? [英] c - why does it make sense that indexing a character pointer is an int?

查看:120
本文介绍了Ç - 为什么它是有意义的索引字符指针是一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *a = "apple";
printf("%s\n", a);  // fine
printf("%s\n", a[1]);  // compiler complains an int is being passed

为什么索引一个字符串的指针给我一个int?我期待它只是打印字符串开始在一个位置(这实际上是当我使用&放大器会发生什么;一个[1] 来代替)。为什么我需要得到的地址?

Why does indexing a string pointer give me an int? I was expecting it to just print the string starting at position one (which is actually what happens when i use &a[1] instead). why do i need to get the address?

推荐答案

这仅仅是 [] 运营商是如何定义的 - A [1] ,当 A 的char * ,取了一个焦 A A [0] 是第一个指出)。

That's just how the [] operator is defined - a[1], when a is a char *, fetches the next char after the one pointed to by a (a[0] is the first one).

难题的第二部分是字符值总是被晋升为 INT (或很少, unsigned int类型)时,作为一个函数的可变长度参数列表的一部分通过。

The second part of the puzzle is that char values are always promoted to int (or rarely, unsigned int) when passed as part of a function's variable-length argument list.

A 等同于&放大器;一个[0] ,并从第一个字符打印 - 因此它是有道理的,&放大器;一个[1] 将打印从第二个字符开始。你也可以使用 A + 1 - 这是完全等价

a is equivalent to &a[0], and it prints from the first character - so it makes sense that &a[1] would print starting from the second character. You can also just use a + 1 - that's completely equivalent.

如果您使用%C 转换说明,打印单个字符,你可以使用 A [1] 只打印第二个字符:

If you use the %c conversion specifier, which prints a single character, you can use a[1] to print just the second character:

printf("%c\n", a[1]);

这篇关于Ç - 为什么它是有意义的索引字符指针是一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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