Disclaimer: I'm relatively new to C/C++ so please let me know if there is anything incorrect or missing in my post. Also, please elaborate as much as possible in your response.

Essentially, what I need to do is the following:
Given a C-style (const char *) string with a value of "<foo>||<bar>", I want to get <foo> in a separate C-string and <bar> in yet another C-string. "||" is a unique, fixed-length delimiter between <foo> and <bar>. The lengths of <foo> and <bar> would be reasonably small, but unknown till runtime.

What is the best way to achieve this?

Well, actually I've put together some code that does provide this functionality. But I've got two concerns, given that I'm new to C/C++ and I've patched this code together using the example found on the strstr documentation page on MSDN and a 'substr' function found with a web search:

  • I get a warning at compile time (below the code listing). What is the meaning of this? Is it safe to ignore? If not, how do I fix it?
  • Overall, is this good "final" quality code? Is there more that can be done for robustness/error-checking etc?


Code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
 
char *substr(const char* fullstr, int start, int end)
{
	char *theSubstring;
	int i, j;
 
	theSubstring = (char*) malloc(end - start + 1);
	for (i = start, j = 0; i < end; ++i, ++j)
	{
		theSubstring[j] = fullstr[i];
	}
	theSubstring[j] = 0;
	return theSubstring;
}
 
void main( void )
{
	char *strstrResult;
	int delimiterLocation;
	char theString[] = "foofoofoo||foobarisnotbarfoo";
	char delimiter[] = "||";
	char *theFoo;
	char *theBar;
 
	printf( "String to be searched:[%s]\n", theString);
	strstrResult = strstr( theString, delimiter );
	delimiterLocation = strstrResult - theString + 1;
	if( strstrResult != NULL )
	{
		printf( "[%s] found at position [%d]\n", delimiter, delimiterLocation);
	}
	else
	{
		printf( "[%s] not found\n", delimiter );
	}
	theFoo = substr(theString, 0, delimiterLocation-1);
	theBar = substr(theString, delimiterLocation+1, (int)strlen(theString));
	printf( "theFoo=[%s] theBar=[%s]", theFoo, theBar);
	free(theFoo);
	free(theBar);
}
I get the following compiler warning:
Code:
~\substring_v2.c(30) : warning C4244: '=' : conversion from '__w64 int' to 'int', possible loss of data
at this line in the code above:
Code:
delimiterLocation = strstrResult - theString + 1;
Is this something to be concerned about? How do I get rid of this warning?



Thanks,
- ak