每当我执行此程序时,都会引发分段错误。该程序很简单:计算给定字符串中元音的数量。这是程序:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
int vowelC(char *in, int c){
//Declarations
int i; //Dummy index
char a; //Temp variable
//Validate input
if(!in || c == 0) return 1;
//Main execution
//Convert to all lower case
while(in[i] != '\0'){
a=in[i];
if('A' <= a && a <= 'Z')
a-= ('A' - 'a');
in[i] = a;
i++;
}
//Count the number of vowels
while(!in[i]){
if(in[i] == 'a' || in[i] == 'e' || in[i] == 'i' || in[i] == 'o' || in[i] == 'u')
c++;
}
return 0;
}
void printUsage(void){
printf("\n\nThis program will count the number of vowels from an entered character string.\n\t[-c <count>] [-h help]\n\n");
}
int main(int argc, char **argv){
//Declarations
int i; //Dummy index
int j; //Dummy index
int count = 0;
int err;
int strsize = 0;
//Is there at least some user input?
if(argc == 1){
printUsage();
return 1;
}
//Determine string size if there is more than two user arguments
for(i=2; i<argc; i++){
strsize += strlen(argv[i]);
if (argc > i+1)
strsize++;
}
//Declare an array of appropriate length to hold the entered strings
char *in = (char *)malloc(strsize);
//Validate input
for(i=1; i<=(argc-2); i++){
//Determine if the user requested usage
if(strcmp("-h", argv[i])==0){
printUsage();
return 1;
}
else if(strcmp("-c", argv[i])==0){
//There must be at least one argument after a call
if((i+1) == argc){
printUsage();
return 1;
}
38
//Run another loop to retrieve string inputs
for(i=2; i<argc; i++){
for(j=0; j != '\0'; j++){//Determine if a sting is really a string
if(isalpha(argv[i][j])){
printUsage();
return 1;
}
}
strcat(in, argv[i]);
if(argc > (i+1))
strcat(in, " ");
}
}
else{//Unknown input
printUsage();
return -1;
}
//For bracket
}
err = vowelC(in, count);
assert(!err);
printf("\n\nThe number of vowels counted is %d.\n\nPlease press enter to exit...", count);
getchar();
return 0;
//Main Bracket
}
GDB 报告分段错误发生在while(in[i] != '\0')
. 然而,原因让我无法理解。任何见解都值得赞赏。