Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.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++_Arrays_Truncation_Strncpy - Fatal编程技术网

C++ 代码崩溃。试图从字符数组C中删除字符

C++ 代码崩溃。试图从字符数组C中删除字符,c++,arrays,truncation,strncpy,C++,Arrays,Truncation,Strncpy,我基本上是在数组中的某个索引之后存储所有内容 例如,我想存储一个声明为char name[10]的名称。如果用户输入15个字符,它将忽略前5个字符,并将其余字符存储在字符数组中,但是,我的程序崩溃了 这是我的密码 char name[10]; cout<< "Starting position:" << endl; cin >> startPos; for(int i= startPos; i< startPos+10; i++) { cout &l

我基本上是在数组中的某个索引之后存储所有内容

例如,我想存储一个声明为
char name[10]
的名称。如果用户输入15个字符,它将忽略前5个字符,并将其余字符存储在字符数组中,但是,我的程序崩溃了

这是我的密码

char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
  cout << i << endl; // THIS WORKS
  cout << i-startPos << endl; // THIS WORKS
  name[i-startPos] = name[i]; // THIS CRASHES
}
字符名[10];
cout startPos;
对于(int i=startPos;icout假设
i
等于3。在循环的最后一次迭代中,
i
现在等于12,所以用12 In代替
i
,最后一行是

name[12-startPos] = name[12];

name[12]
超出了数组的范围。根据您目前所展示的内容,在开始执行此分配之前,
name
中只存储了垃圾,因此您所做的只是重新组织数组中的垃圾。

请以后发布完整的可编译示例。 一个简单的答案是,您的数组可能超出了范围,因为您没有提供完整的示例,所以很难准确地知道

以下是一个工作示例:

#include <iostream>
using namespace std;

int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";

cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
    cout << "max starting point is " <<length-1 << endl;
    return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
  newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " <<  name << " new name: " << newname << endl;
return 0 ;
}
#包括
使用名称空间std;
int main(){
int新_长度,起始时间;
整数长度=15;
字符名称[15]=“McStevesonse”;
cout startPos;

简单地说,如果(new_length)更改为:

for(int i= startPos; i< startPos+10; i++)
for(int i= startPos; i<10; i++)
for(int i=startPos;i

对此:

for(int i= startPos; i< startPos+10; i++)
for(int i= startPos; i<10; i++)

for(int i=startPos;iIf
name
声明为
name[10]
,且
startPos>0
,则
i
将大于10,因此
name[i]
将超出分配的空间进行访问。您发布的代码在该上下文中不是很清楚,因为您用文字描述了其中的一半,而不是在代码中。如何将用户输入的15个字符存储到
字符名[10]
variable?当你知道这个问题的答案时,你就会明白问题是什么。不幸的是,你的程序的这一部分不在你的问题中,因此我无法回答这个问题。但是,我可以告诉你,如果不引起“未定义行为”,就不可能将15个字符存储到10个字符的数组中这通常会导致以后的崩溃。您提供的代码似乎与您提出的问题不相关。
如果用户输入15个字符…
;我看不到您的程序在任何地方询问用户名。请重新表述您的问题和/或包含一个问题。