#include #include // includes NULL==0 #include int main(int argc, char *argv[]) { // argc is count, includes program name // argv[0] is program name // print arguments in reverse order int i; for (i = argc - 1; i > 0; i--) puts(argv[i]); char *suits[] = { "Hearts", "Spades", "Diamonds", "Clubs" }; for (i = 0; i < 4; i++) printf("%d %s\n", strlen(suits[i]), suits[i]); char *s1 = "string 1"; puts(s1); char *s2; s2 = "string 2"; puts(s2); // char s3[]; char s3[100]; // must have size // s3 = "string 3"; // not compatible types s3[0] = 's'; s3[1] = 't'; s3[2] = '\0'; s3[3] = '*'; s3[99] = '$'; puts(s3); // st // s3 = s1; // s3 is constant s2 = s1; // s2[0] = 'P'; // seg fault // *s2 = 'P'; // seg fault // can't change contents of string if allocated as literal printf("%p %s\n", s2, s2); printf("%p %s\n", s1, s1); s2 = s3; // point to same memory array s2[0] = '*'; printf("%p %s\n", s2, s2); printf("%p %s\n", s3, s3); char s4[] = "string 4"; puts(s4); // s4 = s1; // incompatible types s4[0] = '*'; // strcpy(to, from) - up to you that to is big enough to hold from strcpy(s3, s4); puts(s3); /* doesn't work because s5 doesn't point to any memory char *s5; strcpy(s5, s4); puts(s5); */ char *s5 = "l;skdj fowiealskdjfg;oiewasd"; // strcpy(s5, s4); // seg fault because s5 memory immutable puts(s5); char s6[strlen(s4) * 2 + 1]; strcpy(s6, s4); puts(s6); strcat(s6, s4); puts(s6); /* char *s7 = NULL; gets(s7); // seg fault because s7 is NULL */ char *s7; // random junk value // gets(s7); // causes compiler warning because unsafe // also causes seg fault when run // puts(s7); // seg fault // printf("%p\n", s7); s7 = "s7 init"; puts(s7); char s8[10]; puts("enter string: "); fgets(s8, 10, stdin); // safe way, reads 9 chars or less, puts in \0 puts(s8); strcat(s8, "hello"); puts(s8); /* other string functions in string.h char *strcpy(char *to, const char *from) char *strcat(char *to, const char *from) int strlen(const char *s) int strcmp(const char *s1, const char *s2) in stdio.h puts(s) fgets(s,SIZE,stream) in stdlib.h double atof(const char *s) int atoi(const char *s) double strtod(const char *s, char **endp) */ char *line = " 123.45 other stuff"; char *s; double d; d = strtod(line, &s); printf("d=%f s=%s line=%s\n", d, s, line); int month = 0, day = 0, year = 0; char *date = "4/23/2010"; const char *DELIM = "/ "; // use '/' and ' ' (space) to break apart char *token; // token = strtok(date,DELIM); // can't use on string literals // because strtok changes the original string char dateVar[11]; strcpy(dateVar, date); // copy from literal date to variable printf("dateVar before month taken: %s\n", dateVar); token = strtok(dateVar, DELIM); month = atoi(token); printf("dateVar after month taken: %s\n", dateVar); day = atoi(strtok(NULL, DELIM)); year = atoi(strtok(NULL, DELIM)); printf("%d-%d-%d\n", month, day, year); printf("%02d-%02d-%04d\n", month, day, year); return 0; }