I am new to C and have hit a problem with an example form K&R C ( section 1.9) not working properly. Here is the code I have copied from the example, and gone over once looking for discrepancies:
#include <stdio.h>
#define MAXLINE 1000
int mygetline(char line[], int maxline);
void copy(char to[], char from[]);
// print longest input line
main() {
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = mygetline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) // there was a line
printf("%s", longest);
return 0;
}
// getline: read a line into s, return length
int mygetline(char s[], int lim) {
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
// copy: copy 'from' onto 'to'; assume to is big enough
void copy(char to[], char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != "\0")
++i;
}
When I compile I get the following:
cc -Wall -g test.c -o test
test.c:9:1: warning: return type defaults to ‘int’ [-Wreturn-type]
test.c: In function ‘copy’:
test.c:45:30: warning: comparison between pointer and integer [enabled by default]
test.c:45:30: warning: comparison with string literal results in unspecified behavior [-Waddress]
When I run the program, this happens:
j
on@jon-G31M-ES2L:~/c$ ./test
Hello, does this work?
Segmentation fault (core dumped)
I am using gcc as my compiler.
The problem lies in the below line:
It should be
Now, as to why the first one was wrong. “\0” is actually a string literal which is stored in some memory (let’s say the address is 0x7d5678 just for example), whereas the left side of != is an integer. The compiler automatically knows that such a comparison is wrong and can never pass, so it gives you the warning
Also, when you have a string literal in your code, you have no control as to, at what address will it be stored, so the compiler again knows that any comparison with a string literal is wrong hence flags the warning
Also, as an additional note, always remember that strings in C can be compared & manipulated only using the strcmp or strncmp group of string functions. You can never do an “=” comparison on a string.
Hope this helps in understanding.