基本的に、あなたが必要とするすべてが行うことですが、以下である:今
int main(int argc, char * argv[]) {
// check if there's an argument to test
if (1 > argc) {
// extract the position of the last character
int last_pos = strlen(argv[1])-1;
// compare the last character with the character "b"
if (0 <= last_pos && 'b' == argv[1][last_pos]) {
printf("Hoora! The input ends with b!");
return 0;
} else {
printf("Bummer… The input does not end with b :(");
}
} else {
printf("there's no argument to test!");
}
}
、ここで間違っている内容の要約です:
int main(int argc, char * argv[])
{
char strin[250];
int length;
printf("The argument supplied is %s\n", argv[1]);
// you're doing a copy from the first argument into the
// variable strin. If argv[1] is 251 characters, you'll
// overwrite memory, and will cause a "buffer overflow".
// Whenever you need to do strcpy of data input by a user
// use strncpy().
strcpy(strin,argv[1]);
// you're extracting the /length/ of the string, not the /position/
// of the last character, so when you're trying to access at index
// length, you'll get data from one character beyond the array.
length = strlen(strin);
// so here you're seeing a random value from the memory of your computer
printf("Testing: %c",strin[length]);
// here you made a mistake and you're assigning the value 'b' to the
// value beyond the allocated memory for the array. Basically:
// Here be dragons.
// To avoid that mistake, always put the value you're comparing against
// in a comparaison on the Left Hand Side, and the value you're comparing
// on the right hand side. Then the compiler will yell at you!
if(strin[length] = 'b')
{
printf("b in the input");
}
}
出典
2016-09-30 15:14:07
zmo
'strin [長さ]' - > ' strin [length-1] ' –
はテストで=の代わりに==を使用します。 –
割り当て:' strin [length] = 'b'';比較: 'strin [length] == 'b'' – pmg