I have built a function that searchs a subtring in a source string and fills an array with the index of the subtring found it.
I debug it and the array of index fills with the correct index but when i return the pointer and tried to print it, just get blank
#include <stdlib.h>
#include <string.h>
#define AUX_LENGTH 1000
char* find_sub_string(char *source,char *sub_string);
int main()
{
char text[]="yesterday i was walking";
char find[]="e";
printf("%s \n",find_sub_string(text,find));
return 0;
}
/*!
*Function to find the index of a substring in a source string
@param *source string source to search
@param *sub_string substring to find
@return result returns the indexs of the found subtring
@return NULL in case not found or subtring bigest than source string
*/
char* find_sub_string(char *source,char *sub_string)
{
size_t l_source=strlen(source);
size_t l_sub_string=strlen(sub_string);
if(l_sub_string>l_source)
return NULL;
char aux[AUX_LENGTH]="";
static char result[AUX_LENGTH];
int i,j;
for(i=0,j=0; i<l_source;i++)
{
memcpy(aux,source+i,l_sub_string);
if (memcmp(aux,sub_string,l_sub_string)==0)
{
result[j++]=i+1;
}
}
result[j]='\0';
if (j>0)
return result;
else
return NULL;
}
Edit: Example
char text[]="yesterday i was walking";
char find[]="e";
char *p=find_sub_string(text,find);
*p must be a pointer char arra with the index of the position founded, like this: *p={"25"} two and five are the postions of "e" i the source.
Edit 2 I change the code to an array of size_t is more easy to handle without the ASCII convertion, i could use strstsr but i must to embeded in anohter function because i would like to search in all the string and not keep just with the first math.
Here the new code thanks for the comments i could improve a couple of things i will prove with strstr:
size_t* find_sub_string(char *source,char *sub_string)
{
size_t l_source=strlen(source);
size_t l_sub_string=strlen(sub_string);
if(l_sub_string>l_source)
return NULL;
size_t *result = malloc(sizeof(size_t)*AUX_LENGTH);
size_t i,j;
for(i=0,j=0; i<l_source;i++)
{
if (memcmp(source+i,sub_string,l_sub_string)==0)
{
result[j++]=i+1;
}
}
result[j]='\0';
if (j>0)
return result;
else
return NULL;
}
int main()
{
char text[]="yesterday i was walking";
char find[]="y";
size_t *p=find_sub_string(text,find);
printf("%lu \n",p[0]);
return 0;
}