-
array and char confusion
Code:
char buffer[256] = "abcde~fghij~klm"
=====
char *full_parm(const char *bufferx, int parm_index )
{
int parm1_bookmark = 0;
int parm2_bookmark = 0;
char temp[10];
int i = 0;
int j=0;
for(i=0; i<256; i++) // bookmarks the 2 bookmarks
{
if (bufferx[i] == '~')
{
if (parm_index == 1)
{
for(j=0; j <= (i-1); j++)
{ *temp = bufferx[j];
temp++;
}
parm1_bookmark = (i+1);
return temp;
}
parm1_bookmark = ( i+1);
}
else if ( (bufferx[i] == '~') && (parm1_bookmark != 0) )
{
if (parm_index == 2)
{
for(j=parm1_bookmark; j<= (i-1); j++)
{ *temp = bufferx[j];
temp++;
}return temp;
}
parm2_bookmark = (i+1);
}
else if ( (bufferx[i] == '~') && (parm2_bookmark != 0) )
if (parm_index == 3)
{
for(j=parm2_bookmark ; j <=(i-1); j++)
{
*temp = bufferx[j];
temp++;
}return temp;
}
}
}
basically what i am trying to do is to sections out the useful portion of the buffer and ignore the garbage.
if i enter full_parm(buffer, 1)
i hope function to return "abcde"
if i enter full_parm(buffer, 2)
i hope function to return "fghij"
but i have been unsucessful so far
i suspect it's me writing the arrrays wrongly
any idea what's wrong with my code?
-
> temp++;
Arrays cannot be incremented
Use
temp[index++] = something;
Don't forget
temp[index] = '\0';
to make the string complete
> return temp;
You cant return the address of a local variable.
The quick fix in this instance is to make your temp static, like so
static char temp[10];
> for(i=0; i<256; i++)
Use strlen() of the input buffer.
A better answer all over would be
char *full_parm(const char *bufferx, int parm_index, char *temp, size_t temp_size )
This is the fgets() approach - the caller provides the space and says how big that space is, and then life is much easier for the called function.