Hi All
I want to compare a 'const *chars' with a *char using strcmp. If I use printf
Code:
printf("v1=|%s| v2=|%s|\n", props[0].name, config_key) ; // -> v1=|hello| v2=|hello|
printf("l1=%d l2=%d\n", strlen(props[0].name), strlen(config_key) ) ; // --> l1=5 l2=6
they look identical, but have a different length (This is on Linux, on my Mac both are 5 and the issue does not exist)
Both originate from a different source. v1:
Code:
struct propentry
{
ptrdiff_t offset;
const char *name;
};
#define PE(a) { offsetof(struct CONFIG, a), #a }
struct propentry props[] =
{
PE(hello)
} ;
and v2:
Code:
FILE *fp = fopen( filename, "r" ) ;
char line [ 128 ];
while(fgets(line, sizeof(line), fp) != NULL)
{
... determine pos ...
char *config_key = malloc( pos * sizeof(*config_key) + 1 ) ; // add 1 for 'null termination'
substring( config_key, line, 0, pos ) ;
....
}
....
void substring(char* dest, const char* src, int start, int stop)
{
if ( stop == -1 )
stop = strlen(src) ;
strncpy( dest, src + start, stop ) ; // doesn't copy '\0' (null termination)
dest[strlen(dest) ] = '\0' ; // null termination
}
and I compare them like
Code:
if ( strcmp( props[0].name, config_key) == 0 ) { ... }
I would say I do something wrong with the 'null termination', but I can't figure it out. Any suggestions ?
Cheers
Luca