在C ++中使用指针将一个数组复制到另一个数组的问题

时间:2019-06-03 19:48:58

标签: c++ arrays pointers char

我是一所在线大学的学生,有一个关于将一个填充的数组复制到另一个空数组的演讲,我不太理解,即使通过给定的代码行我也无法获得所需的结果。 (请注意,在视频讲座中,他们没有“提示”检查代码是否有效)。

ptrA = str1;
ptrB = str2;

while(*ptrA != '\0'){
cout << *ptrA;    // it works fine shows output
ptrA++;
}

while(*ptrA != '\0'){
*ptrB++ = *ptrA++;
}
*ptrB = '\0';

while(*ptrB != '\0'){
cout << *ptrB;     // this doesn't show any thing and crashes
ptrB++;
}

第一个cout效果很好,显示了输出“正在播放指针”,但是将str1复制或复制到str2之后,最后一个输出不起作用。

2 个答案:

答案 0 :(得分:0)

对于每个ptrB++,您将指针移到ptrB最初的起始位置。因此,如果不将ptrB重置为相应字符串的开头,就不能在第二个循环中使用ptrAptrA = str1; while(*ptrA != '\0'){ *ptrB++ = *ptrA++; } *ptrB = '\0'; ptrB = str2; while(*ptrB != '\0'){ cout << *ptrB; ptrB++; } 同样如此:

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container .cube-container {
perspective: 800px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.container .cube-container .cube {
transition: transform 2s ease-in;
transform-style: preserve-3d;
width: 150px;
height: 150px;
margin: 50px 0;
}

.box {
width: 100%;
height: 100%;
position: absolute;
color: white;
text-transform: uppercase;
letter-spacing: 0.08em;
font-family: 'Roboto', sans-serif;
font-size: 20px;
font-weight: 500;
display: flex;
justify-content: center;
align-items: center;
}

.box.front {
background: #40b9dc;
transform: translateZ(75px);
}

.box.back {
background: #3dbadf;
transform: translateZ(-75px) rotateY(180deg);
}

.box.top {
 background: #5acaec;
 transform: rotateX(-90deg) translateY(-75px);
 transform-origin: top center;
}

.box.bottom {
background: #82daf4;
transform: rotateX(90deg) translateY(75px);
transform-origin: bottom center;
}

.box.left {
background: #a3e5f9;
transform: rotateY(270deg) translateX(-75px);
transform-origin: center left;
}

.box.right {
background: #67d6f7;
transform: rotateY(-270deg) translateX(75px);
transform-origin: top right;
}

答案 1 :(得分:0)

您正在递增指针,然后以某种方式期望它们再次指向字符串的开头。您可能想再次将指针重置为开头

onEditingFinished

请注意,您的代码中有

auto beginA = ptrA;
auto beginB = ptrB;

while(*ptrA != '\0'){
    cout << *ptrA;    // it works fine shows output
    ptrA++;
}

ptrA = beginA;  // reset to beginning, otherwise ptrA == '\0'

while(*ptrA != '\0'){
    *ptrB++ = *ptrA++;
}
*ptrB = '\0';

ptrB = beginA;

while(*ptrB != '\0'){
    cout << *ptrB;     // this doesn't show any thing and crashes
    ptrB++;
}

ie while循环没有打印任何东西,因为它从未执行过。复制数据的循环也是如此:在第一个循环*ptrB = '\0'; while(*ptrB != '\0'){ 之后。