Char* 字符数组,但 int* 不是整数数组? [英] Char* array of chars, but int* not array of ints?

查看:57
本文介绍了Char* 字符数组,但 int* 不是整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C99 中,通常使用 char* 数据类型初始化字符串,因为没有原始的字符串"数据类型.通过将第一个字符的地址存储在变量中,这有效地创建了一个字符数组:

In C99 a string is typically initialized by using the char* data type since there is no primitive "string" data type. This effectively creates an array of chars by storing the address of the first char in the variable:

FILE* out = fopen("out.txt", "w");
char* s = argv[1];
fwrite(s, 12, 1, out);
fclose(out);
//successfully prints out 12 characters from argv[1] as a consecutive string.

编译器如何知道char* s 是一个字符串而不仅仅是单个char 的地址?如果我使用 int* 它将只允许一个 int,而不是它们的数组.为什么会有不同?

How does the compiler know that char* s is a string and not just the address of a singular char? If I use int* it will only allow one int, not an array of them. Why the difference?

我的主要重点是了解指针、引用和取消引用的工作原理,但整个 char* 一直困扰着我.

My main focus is understanding how pointers, referencing and de-referencing work, but the whole char* keeps messing with my head.

推荐答案

编译器如何知道char* s 是一个字符串而不仅仅是单个字符的地址?

How does the compiler know that char* s is a string and not just the address of a singular char?

它没有.就编译器"而言,char* s 是一个指向 char 的指针.

It doesn't. As far as "the compiler" is concerned, char* s is a pointer to char.

另一方面,有许多库函数假设 char* 指向 char 的空终止序列(参见例如 strlen, strcmp 等).

On the other hand, there are many library functions that assume that a char* points to an element of a null-terminated sequence of char (see for example strlen, strcmp etc.).

请注意 fwrite 并没有做出这个假设.它要求你告诉它你想写入多少字节(并且这个数字不会让你超出第一个参数所指向的缓冲区的范围.)

Note that fwrite does not make this assumption. It requires that you tell it how many bytes you want to write (and that this number doesn't take you beyond the bounds of the buffer pointed at by the first argument.)

如果我使用 int* 它将只允许一个 int,而不是一个数组.为什么会有不同?

If I use int* it will only allow one int, not an array of them. Why the difference?

这是错误的.C 语言没有 char* 的特殊情况.int* 也可以指向 int 数组的元素.实际上,您可以编写一个使用 0 或另一个标记值来指示 int 序列的结尾的库,并且使用它与 char* 按惯例使用.

That is incorrect. The C language does not have a special case for char*. An int* can also point to an element of an array of int. In fact, you could write a library that uses 0 or another sentinel value to indicate the end of a sequence of int, and use it much in the same was as char* are used by convention.

这篇关于Char* 字符数组,但 int* 不是整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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