Access violation reading Location (Visual Studio C++)

5.1k views Asked by At

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.

Error:

Unhandled exception at 0x54E0F791 (msvcr110d.dll) in <filename>.exe: 0xC0000005: Access violation reading location 0x00000065

Here is my Code:

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];
1

There are 1 answers

5
HadeS On

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);

Problem in your code is strcat(sub[0],(char*)S[j-1]);, you are trying to cast char as character pointer.

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: signature of strcat is

char * strcat ( char * destination, const char * source );