2

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];
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Anup Agarwal
  • 53
  • 1
  • 8

1 Answers1

2

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 );
HadeS
  • 2,020
  • 19
  • 36
  • Actually I wanted to concatenate only a substring of S to sub[0] the above is just an example. Thanks First of all the code works now. I understand how passing address of S[..] in strcat will work, but I still don't understand what is the problem of explicitly converting char to char*, according to me that should do the same job. – Anup Agarwal Jun 24 '15 at 16:43
  • Actually it did not Work, If I do &S[j-1] then whole of the string after j-1 gets concatenated, I want only a specific range of characters in the array to get concatenated and so I am using a loop to set range and individually concatenating each character in the array – Anup Agarwal Jun 24 '15 at 17:23
  • show me some example so that I can get better idea what you are trying to achieve – HadeS Jun 24 '15 at 17:25
  • Basically could you just tell me how I can concatenate single character present at ith location in S Array to sub[j] 2d array. I am trying to make a program that lists all possible substrings of a given string. – Anup Agarwal Jun 24 '15 at 17:31
  • if you use `std::string` class you simply have to add whatever character you want to add. but if you want to stick to `char array` things will become tricky. And Reason why `(char*)S[j-1]` will cause crash is because S is holding character all characters are integer value (ascii value). now casting any number to pointer type will not cause any problem until you access it. – HadeS Jun 24 '15 at 17:58