Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制带指针和不带指针的字符数组_C++_C++11 - Fatal编程技术网

C++ 复制带指针和不带指针的字符数组

C++ 复制带指针和不带指针的字符数组,c++,c++11,C++,C++11,有人能帮我吗。我正在尝试使用char数组(在第一种情况下)和指针(在第二种情况下)复制字符数组。在第一种情况下,我理解为什么需要在while循环之后立即使用temp[I]='\0',但在第二种情况下,我不理解为什么不需要在while循环之后使用temp[I]='\0' 1st case: char source[50] = "Hello World"; char temp[50]; int i = 0; while (source[i] != '\0')

有人能帮我吗。我正在尝试使用char数组(在第一种情况下)和指针(在第二种情况下)复制字符数组。在第一种情况下,我理解为什么需要在while循环之后立即使用temp[I]='\0',但在第二种情况下,我不理解为什么不需要在while循环之后使用temp[I]='\0'

               1st case:
char source[50] = "Hello World";
char temp[50];
int i = 0;

    while (source[i] != '\0')
    {
        temp[i] = source[i];
        i++;
    }
    temp[i]='\0';
    cout << temp;

                  2nd Case:

char source[50] = "Hello World";
char *temp=source;
int i = 0;

while (source[i] != '\0')
{
    temp[i] = source[i];
    i++;
 }
cout << temp;
第一种情况:
char source[50]=“你好世界”;
煤焦温度[50];
int i=0;
while(源[i]!='\0')
{
温度[i]=源[i];
i++;
}
温度[i]='\0';
库特
我理解为什么在第一种情况下,在while循环之后需要一个temp[I]='\0'

是的,因为您在复制
'\0'
之前停止了循环,所以您必须在最后人工执行此操作

我不明白为什么在第二种情况下,在while循环之后我不需要它

               1st case:
char source[50] = "Hello World";
char temp[50];
int i = 0;

    while (source[i] != '\0')
    {
        temp[i] = source[i];
        i++;
    }
    temp[i]='\0';
    cout << temp;

                  2nd Case:

char source[50] = "Hello World";
char *temp=source;
int i = 0;

while (source[i] != '\0')
{
    temp[i] = source[i];
    i++;
 }
cout << temp;
因为
temp
不是一个新数组,它只是一个指向旧数组元素的指针。该循环中的每个赋值都类似于
x=x
:您只是在用数组本身覆盖数组

您不需要添加
'\0'
,因为源数组是目标数组,所以它已经存在


从逻辑上讲,第二种情况下的代码一无所获。

在轨比赛。我考虑过你刚才说的话,我完全理解。非常感谢。我也误解了很多事情。如果我错了,请再次更正,但我认为temp指向堆栈本身上的源元素。只有当我们使用new操作符时,指向heapComments上元素的指针才不用于扩展讨论;这段对话已经结束。