You probably won't get along without defining a maximum size.
It is not important not to define a size, but to know and respect it afterwards.
The easiest way to get input from a user is fgets()
:
char string1[50];
fgets(string1, sizeof string1, stdin);
Of course, you should check its return value.
If you want to accept (almost) any length, you can try the solution I gave here.
This is required to prevent an overflow of the given array. In order to work with the string, you can get its length wither with strlen()
, or, if you are not allowed to use that or are walking to the strings nevertheless, by counting the characters until you hit a NUL byte.
The background of this is that strings in C are terminated by a NUL byte. They are sequences of char
s, and the NUL byte (0, not '0'
which would be 48) terminates this sequence.
If your only task is to verify that the strings you read are small enough, and complain if they aren't, then just do that :-)
int main(int argc, char ** argv)
{
char string2[50]; // larger than required; in order to be able to check.
char string1[30]; // if all is ok, you have maximum length of 29, plus the NUL terminator. So 30 is ok.
char * ret = fgets(string2, sizeof string2, stdin);
if (!ret) {
fprintf(stderr, "Read error.\n")
return 1; // indicate error
}
if (strlen(string2) >= sizeof string1) { // we can take this size as a reference...
fprintf(stderr, "String 1 too long.\n")
return 1; // indicate error
}
strcpy(string1, string2); // as we have verified that this will match, it is ok.
// Otherwise, we would have to use strncpy.
// Now read the 2nd string by the same way:
ret = fgets(string2, sizeof string2, stdin);
if (!ret) {
fprintf(stderr, "Read error.\n")
return 1; // indicate error
}
if (strlen(string2) >= sizeof string1) { // we can take this size as a reference...
fprintf(stderr, "String 2 too long.\n")
return 1; // indicate error
}
// Now we know that both strings are ok in length an we can use strcmp().
int c = strcmp(string1, string2);
printf("strcmp() result: %d.\n", c);
return 0; // indicate success
}
I am not clear now if you are supposed to implement strcmp()
as well. If so, I'll leave that as an exercise.