URGENT help needed in implmenting substring for cstring!!

#include<iostream>
#include<string>

using namespace std;

char* substring (char *s, int start, int end);

int main()
{
char *s="university";
char *ans;
int start, end;

ans=substring(s, 2, 5);
cout<<ans<<endl;

system("pause");
return 0;

}

char* substring (char *s, int start, int end)
{
char *ptr=NULL;
char *p=s;
for(int i=0;i<(end-start); i++)
{
*(ptr+i)=*(p+i);
}
*(++ptr)='\0';
return ptr;
}
Last edited on
1. You did not explain what your problem is.
2. Use the code tags. They are there for a reason.

Looking at it quickly, the problem is most likely because you are trying to modify something that is put in the read-only data section of the program.

This seems to be a simple homework/assignment, so don't expect any of us to answer any more than what I said. Try to understand what my answer means first before you go follow up on this question. We like to help, but we don't want to spoon feed people.
The problem is that I'm trying to get a substring from a string which has been read as a character, using the start and end values I have to extract the substring into another character pointer. I'm very new to c-string, thus some help would be valuable!!
I dnt get what ur trying to say abt the trying to modify something tht is put in the read only data section of the program!! Thank you!!
You are copying the substring in the function but right after that you are giving a null to 2nd index which emties your string.
moreover you need new memory for substring therefor you can use "new" keyword for memory

correct program is here


#include<string>

using namespace std;

char* substring (char *s, int start, int end);

int main()
{
char *s="university";
char *ans;
//int start, end;

ans=substring(s, 2, 5);
cout<<ans<<endl;

system("pause");
return 0;

}

char* substring (char *s, int start, int end)
{
char *ptr=new char[end-start+1];
for(int i=0;i<(end-start); i++)
{
*(ptr+i)=*(s+i+start);
}
*(ptr+end-start)='\0';
return ptr;
}

I dnt understand how the 2nd index gets the NULL, can u explain tht further, would be highly appreciated!! Thank yoooou!!
Topic archived. No new replies allowed.