问题描述
我正在尝试形成给定字符串的子字符串,以便动态分配字符串和子字符串,子字符串是二维数组,因为它将包含多个子字符串.
I am trying to form substrings of a given string, so that both string and substring are dynamically allocated, substring is 2D array as it will contain multiple substrings.
我不知道我哪里出错了.
I can't figure out where I am going wrong.
错误:
Unhandled exception at 0x54E0F791 (msvcr110d.dll) in <filename>.exe: 0xC0000005: Access violation reading location 0x00000065
这是我的代码:
char **sub = new char* [10];
sub[0] = new char [10];
strcpy(sub[0],"");
char *S = new char[10];
strcpy(S,"");
cin.getline(S,10);
for(int j = 2; j<10; j++)
strcat(sub[0],(char*)S[j-1]);
cout<<sub[0];
推荐答案
从您的代码看来,您的意图是将 sub[0]
连接到 S
.简单的解决方案是删除 for 循环并简单地编写.
As it seems from your code that your intent is to concatenate sub[0]
to S
.Simple solution will be remove for loop and simply write.
strcat(sub[0],S);
您代码中的问题是strcat(sub[0],(char*)S[j-1]);
,您试图将 char 转换为字符指针.
Problem in your code is strcat(sub[0],(char*)S[j-1]);
, you are trying to cast char as character pointer.
现在我在您的代码中看到的另一件事是您还没有从第 0 个索引开始访问 S
.这可能是您的要求.如果您想从 index 1
进行连接,即使这样也有解决方案.
Now other thing which I see in your code is you havn't started accessing S
from 0th index. That might be your requirement or so. Even that has solution if you want to concatenate from index 1
.
strcat(sub[0],&S[1]);
PS:strcat的签名是
PS: signature of strcat is
char * strcat ( char * destination, const char * source );
这篇关于访问冲突读取位置 (Visual Studio C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!