tags:

views:

65

answers:

2
int main(int argc, char** argv) {
    char *test[5][20];
    char *input[20];
    int i;
    for(i=0;i<5;i++){

    printf("enter> ");
    fflush ( stdout );
    fgets(input,20,stdin);
         *test[i] = *input;
    }

    for(i=0;i<5;i++)
       printf("%d | %s\n",i,test[i]);
    return 0;
}

Output:

enter> pwd

enter> pathd

enter> ls

enter> echo $path

enter> pwd 0 | pwd

1 | path▒] a▒▒a▒▒#a▒▒ 2 | ls

3 | echo▒▒( 4 | pwd

Press [Enter] to close the terminal ...

I also need to be able to read in input that has spaces. Thanks!

+1  A: 

Your types are all messed up. A string in C is essentially a pointer to a character which begins a sequence of characters that ends with a null byte.

Input is an array of pointers to characters--or in this purpose, an array of strings. What you're doing is reading 20 characters into input, where input in that fgets expression acts as the address of the first element of the array. So you're reading 20 characters from stdin into input's 20 pointers to characters. This is not what you want. You want to read the characters into space for a string.

I assume you are compiling using GCC--consider using -Wall so GCC warns you about the type issues.

Another issue is

*test[i] = *input;

Since this seems like homework, I feel like I have given enough details.

Kizaru
+1  A: 

Use memcpy(). And you need to strip trailing newlines. Here:

#include <stdio.h>
#include <string.h>

void chopnl(char *s) {              //strip '\n'
    s[strcspn(s, "\n")] = '\0';
}

int main() {
    char test[5][20];
    char input[20];
    int i;
    for(i=0;i<5;i++){
        printf("enter> ");
        fflush ( stdout );
        fgets(input, 20, stdin);
        chopnl(input);
        memcpy(test[i], input, strlen(input)+1);//test[i] = input;
    }
    for(i=0;i<5;i++)
       printf("%d | %s\n",i,test[i]);
    return 0;
}
Ruel
Thanks a lot...one question why strlen(input)+1?
Joe
The third argument in `memcpy()` is the number of bytes to copy. And since `strlen()` returns the actual length of a string, it doesn't include the null terminator `\0`, so you have to allocate space for that.
Ruel
ok thanks again!
Joe