Reputation:
Im trying to return a pointer to a string in my function and assign to another char array to print it out. But i get a conflicting type error for my function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
const char *s = "[[random text]]";
const char *P1 = "[[";
const char *P2 = "]]";
const char *result = parseString(s,P1,P2);
printf("%s",result);
}
void const char* parseString(char* str,char* first, char* snd)
{
char *target = NULL;
char *start, *end;
if ( start = strstr( str, first ) )
{
start += strlen( first );
if ( end = strstr( start, snd ) )
{
target = ( char * )malloc( end - start + 1 );
memcpy( target, start, end - start );
target[end - start] = '\0';
}
}
return target;
}
Upvotes: 0
Views: 31
Reputation: 25271
Your code has the following problems:
You should provide a prototype declaration of the function parseString
before using it in main
.
If you want the function parseString
to return a pointer to a string, then you should make the return type of the function char *
instead of void const char*
.
If you declare the parameters of the function parseString
to be of type char*
, then you are not allowed to pass that function an argument of type const char *
. However, since the function parseString
does not modify the strings pointed to by its arguments, you can declare the parameters to be const char *
instead of char *
, which will solve your problem.
After fixing these issues, your could will look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* parseString( const char* str, const char* first, const char* snd);
int main(int argc, char *argv[])
{
const char *s = "[[random text]]";
const char *P1 = "[[";
const char *P2 = "]]";
const char *result = parseString(s,P1,P2);
printf("%s",result);
}
char* parseString( const char* str, const char* first, const char* snd)
{
char *target = NULL;
char *start, *end;
if ( start = strstr( str, first ) )
{
start += strlen( first );
if ( end = strstr( start, snd ) )
{
target = ( char * )malloc( end - start + 1 );
memcpy( target, start, end - start );
target[end - start] = '\0';
}
}
return target;
}
Upvotes: 1