c - Program keeps returning Segmentation Fault -
i'm new person loves play around coding. going through course on edx, , 1 of exercises need complete has small code snippet keeps on giving segmentation fault. have taken out faulty bit (everything else compiles nicely)
#include <stdio.h> #include <string.h> #include <cs50.h> #include <ctype.h> #include <stdlib.h> int main (int argc, string argv[]) { if (argc == 2 && isalpha(argv[1])) { int = 0; while (argv[1][a] == '\0') { a++; printf("%c\n", argv[1][a]); } } else { printf("usage: ./programname 1-alphabetical word\n"); return 1; } }
the problem seems here: argv[1][a]
can't life of me find out what, , how fix it.
(1) isalpha(argv[1])
wrong. function expects single character, passing pointer-to-string. not give kind of expected result, , it's undefined behaviour bargain. either need loop , check each character, use more high-level library function check entire string, or - quick , sense-changing fix - check 1st character bluepixy suggested: isalpha( argv[1][0] )
or isalpha( *argv[0] )
.
(2) while
condition wrong. telling loop while current character nul
. nothing non-empty strings , hit next problem #3 empty one. presumably meant while (argv[1][a] != '\0')
, i.e. loop until nul
byte reached.
(3) increment index a
before trying printf()
it. index out of range right now, if input string empty, body executes , index beyond terminating nul
. if loop condition fixed, miss 1st character , print terminating nul
, neither of make sense. should increment a
once have verified in-range , done need it. so, printf()
it, then increment it.
2 , 3 seem soluble using for
loop instead of manually splitting initialisation, testing, , incrementing of loop variable. should use correct type indexing: in case wanted print string millions or billions of characters, int
not wide enough, , it's not style. so:
#include <stddef.h> /* size_t */ (size_t = 0; argv[1][a] != '\0'; ++a) { printf("%c\n", argv[1][a]); }
Comments
Post a Comment