Good afternoon. I was wondering why this program with a pointer for arrays with char (*argv)[100] doesn't work at all.
I understand char (*argv)[100] is declaring a pointer for arrays with n lines and a maximum of 13 chars. And char *argv[] is declaring an array for n char pointers (strings). Therefore, I thought the program below would work as expected, printing thames thames thames when I input:
My line of thought was: "well, if I input less than 100 characters, everything will work just fine. "Code:./strcpy thames thames thames
Code:#include <stdio.h> #include <stdlib.h> /* for exit and malloc*/ #include <string.h> #ifndef MAXPOINTERS #define MAXPOINTERS 20 #endif #ifndef MAXCHARS #define MAXCHARS 100 #endif void Strcpy(char*, char*); char** Malloc2D(int, int); void Strcpy(char* s, char* t) { while( (*s++ = *t++) ) ; } char** Malloc2D(int nPointers, int nChars) { int i; char** strings; strings = malloc(nPointers * sizeof(char*)); for(i = 0; i < nPointers; i++) { *(strings + i) = malloc(nChars * sizeof(char)); } return strings; } int main(int argc, char (*argv)[100]) { int i, j; char** s; if(argc < 2) { printf("Please enter [Executable][string]\n"); exit(0); } else if(argc >= MAXPOINTERS) { printf("You can write up to %d words", MAXPOINTERS); exit(0); } s = Malloc2D(MAXPOINTERS, MAXCHARS); for(j = 1, i = 0; i < argc - 1; i++, j++) { Strcpy(s[i], argv[j]); } printf("\nThe strings which were input are:\n\n"); for(i = 0; i < argc - 1; i++) { printf("%d.\t%s\n", i + 1, s[i]); } return 0; }



2Likes
LinkBack URL
About LinkBacks



