I'm trying to use strcmp() to compare to the first letter of the string line (which should be "V") with the letter "V" in c.
I've tried several different methods of trying to create a pointer to only the first letter of the string in order to use to compare. My latest solution seemed to work better but is adding some string of letters after the initial assignment.
printf("test:%c ", line[1]);
char* ch;
ch[0] = line[1];
printf("ch is: %s\n", ch);
printf("strcmp result: %d\n", strcmp(ch, "V"));
line is already initialized as a long string (read from a file). The second letter of line is "V", so I would expect ch = "V". However, these results show up:
test:V
ch is: VL?[?
strcmp result: 76
Similarly, this code:
char ch[1];
ch[0] = line[1];
printf("ch is: %s\n", ch);
printf("strcmp result: %d\n", strcmp(ch, "V"));
provides this incorrect answer: test:V
ch is: V?
strcmp result: 133
Wondering why those extra letters show up in ch, and if there's a better way to do this in general. My entire program relies on reading and comparing certain letters in the string line so this is an essential part of it.
Thanks for your help.
The errors you're getting is because ch
does not point to a null terminated string.
In the first case:
char* ch;
ch[0] = line[1];
The pointer ch
hasn't been initialized, but you then dereference the pointer (implicitly via the array subscript operator []
) in an attempt to write to it. Dereferencing an uninitialized pointer invokes undefined behavior, which in your case gives unexpected output.
Similarly for the second case:
char ch[1];
ch[0] = line[1];
Here ch
is an array of size 1 and you assign a value to that member. But then you pass ch
to strcmp
which expects a null terminated string. Since the array only contains 1 element, there is no space for the null terminator. As a result the strcmp
reads past the end of the array looking for one. Reading past the end of an array also invokes undefined behavior.
To do a proper string comparison, the array must have room for the string in question which means the size must be at least 2:
char ch[2];
ch[0] = line[1];
ch[1] = 0;
However, your goal is not to compare strings. You want to compare a single character instead. To do that, just use single quotes to denote a character constant and compare that directly against the element in question:
printf("test:%c ", line[1]);
printf("strcmp result: %d\n", (line[1] == 'V'));