为什么不存在字符串“存在”和字符的内存与字符串的内存?

时间:2018-05-23 14:49:13

标签: c string

我在大学学习了4个月的C编程。我的教授总是说字符串并不存在。自从我完成了这2个小课程后,我真的开始编程(java)。我不记得为什么字符串不存在。我之前并不关心这件事,但我现在很好奇。他们为什么不存在?它们是否存在于Java中?我知道它必须做一些事情“在引擎盖字符串只是字符”,但这是否意味着字符串都保存为多个字符等?这不是需要更多的记忆吗?

2 个答案:

答案 0 :(得分:3)

C中不存在string 类型,但 C字符串确实存在。它们被定义为空终止字符数组。例如:

char buffer1[] = "this is a C string";//string literal

在内存中创建一个如下所示的C字符串:

|t|h|i|s| |i|s| |a| |C| |s|t\r|i|n|g|\0|?|?|?|  
<                 string               >

请注意,这不是字符串:

char *buffer2;  

在它包含由char终止的一系列\0之前,它只是指向char的指针。 (char *

buffer2 = calloc(strlen(buffer1)+1, 1);
strcpy(buffer2, buffer1); //now buffer2 is pointing to a string  

参考文献:
Strings in C 1
Strings in C 2
Stirngs in C 3
and many more...

<强> 编辑:
(以解决关于字符串的评论中的讨论:)

基于以下定义:(来自 here

  

字符串实际上是一维字符数组   空字符'\ 0'。

首先,因为 null终止是关于C字符串的对话的组成部分,所以这里有一些说明:

  • 术语NULL指针,通常定义为(void*)0),或者 只是0。它可以是,通常用于初始化指针 变量
  • 术语'\ 0'是字符。在C中,它意味着完全相同 作为整数常量0的东西。 (相同值0,相同类型 int)。它用于初始化char数组。

字符串的内容:

char string[] = {'\0'}; //zero length or _empty_ string with `sizeof` 1.    

在记忆中:

|\0|

...

char string[10] = {'\0'} also zero length or _empty_ with `sizeof` 10.   

在记忆中:

|\0|\0|\0|\0|\0|\0|\0|\0|\0|\0|  

...

char string[] = {"string"}; string of length 6, and `sizeof` 7.    

在记忆中:

|s|t|r|i|n|g|\0|  

...

char [2][5] = {{0}}; 2 strings, each with zero length, and `sizeof` 5.    

在记忆中:

|0|0|0|0|0|0|0|0|0|0| (note 0 equivalent to \0) 

...

char *buf = {"string"};//string literal.    

在记忆中:

|s|t|r|i|n|g|\0|

不是字符串的东西:

char buf[6] = {"string"};//space for 6, but "string" requires 7 for null termination.   

记忆中:

|s|t|r|i|n|g|  //no null terminator
          |end of space in memory.   

...

char *buf = {0};//pointer to char (`char *`).  

在记忆中:

|0| //null initiated pointer residing at address of `buf`  (eg. 0x00123650)

答案 1 :(得分:2)

C中不存在字符串作为数据类型。有int,char,byte等,但没有“string”。

这意味着您可以将变量声明为int,但不能将其声明为“字符串”,因为没有名为“string”的数据类型。

最接近C的字符串是字符数组,或者是内存部分的char *。实际的字符串由程序员定义,作为以\ 0结尾的字符序列,或具有已知上限的多个字符。