I can't understand why this code is throwing an unhandled "Access Violation" exception. It's a simple program that attempts to copy one char pointer string to another while skipping some characters (chars at index: 3,4,5)
#include <conio.h>
#include <iostream>
using namespace std;
void main()
{
char str[20];
char *str1 = "abcdeabcde", *str2 = "";
int i, dx = 0;
for(i=0; *(str1+i)!='\0'; i++)
if(i<3 || i>5)
{
*(str2 + dx) = *(str1 + i);
dx++;
}
*(str2+dx) = '\0';
cout<<str2;
_getch();
}
Whereas the assignment using syntax *(str + i)
works fine in the following function code (it's an implementation of getline)
int getstr(char *str, int n)
{
char ch;
int i = 0;
for(i=0; i<n && (ch = _getch())!= '\r'; i++)
{
if(ch == '\b')
{
if(i == 0)
{
i = -1; continue;
}
else
{
cout<<"\b \b";
i -= 2;
}
}
else if(ch > 31 && ch < 127 && i<n-1)
{
cout<<ch;
*(str + i) = ch;
}
else
{
cout<<"\a";
i--;
}
}
*(str + i) = '\0';
return i+1;
}
So why does this work in the second case but not in first?