There are various problems with your code, not just a simple bug. I'll try to describe some of them here.
Turn on compiler warnings. For example, if your array is size 30, there is no element at index 30 (indexes would go from 0 to 29). Your compiler could have warned you about that and other problems.
Store a string in a char
array or pointer, but not in a char
pointers array. When you wrote:
char *str1[MSL]
You are creating an array of pointers to char
, or an array of strings. However, since you're dealing with pointers to char
as strings, you'd need to allocate space for them yourself. That's another concept. You probably meant to write an array of char
like this:
char str1[MSL]
char *p, *q, str1[MSL], str2[MSL]; /* in your declaration */
Enter at maximum 29 characters. If your string holds 30 char
, and you need 1 to mark the null at the end, you've got 29 remaining usable char
s. Or… change MSL
to 31.
Consider dropping the \n
from your scanf
format. It will make it read all whitespace (which is what \n
represents in a format) waiting for the next non-whitespace. Thus, the input somestring<enter>
for example won't be sent directly to your program until the next non-whitespace or EOF.
Give scanf
an address. That could be just the array name (which translates to the first element address) or a pointer if you were working with them.
scanf("%s", str1);
scanf("%s", strptr); /* strptr is a char pointer pointing
to previously allocated space */
You can limit the length of what scanf
reads. To be safe:
scanf("%29s", str1);
Don't use uninitialised data in comparisons. When you wrote if(str1[MSL+1] != '\0')
, what did you expect str1
to contain if you had never stored anything yet?
int
main(int argc, char **argv)
{
char *p, *q, str1[31], str2[31]; /* a lot of unused variables */
printf("Please enter a string of maximum 30 characters: ");
scanf("%30s", str1);
printf("%s\n", str1);
return 0;
}