2

So I'm reading in chars one by one from a file:

char temp[3];

temp[0] = nextchar;
printf("%c",temp[0]); //prints %

temp[1] = nextchar = fgetc(srcptr);
printf("%c",temp[1]); //prints 2

temp[2] = nextchar = fgetc(srcptr);
printf("%c",temp[2]); //prints 0

if(strcmp(temp, "%20") == 0) { printf("%s","blahblah"); }

Ideally this should print "blahblah" at the end. However, it doesn't. So why is strcmp returning 0, and more importantly: how can I fix it?

varatis
  • 14,494
  • 23
  • 71
  • 114

3 Answers3

9

You need to null terminate temp.

EDIT

Change char temp[3]; to char temp[4]; temp[3] = 0;

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
6

Use memcmp instead, because strcmp expects both strings to be '\0'-terminated (and temp is not):

if(memcmp(temp, "%20", sizeof(temp)) == 0) { printf("%s","blahblah"); }
Daniel Roethlisberger
  • 6,958
  • 2
  • 41
  • 59
3

A string is an array of characters, ending with the '\0' character. Since your tmp array can hold three characters and none of them is the terminating null character, strcmp (and any other string function) will think it continues further, reading memory past the allocated space until it encounters a null character (or crashes as it tires to read a restricted memory space).

The string "%20" is really the characters: '%', '2', '0', '\0'

So the easiest way to fix it is to declare tmp one larger and assign '\0' to the last element:

char tmp[4];
...
tmp[3] = '\0';
Attila
  • 28,265
  • 3
  • 46
  • 55