0

I am working on a project that will require me to keep an array of the 10 most recently entered commands from a user, and created a small test program to ensure I could actually create an array of 10 strings and print it back out. The code copied below generates "Segmentation fault: 11" when run, even though it compiles with no warnings or errors. I am very new to c and I know that this task will require some combination of pointers to arrays of characters, but I cannot seem to get it working. What do I need to do to be able to overwrite the string at any of the 10 indices in 'history' and print the current history array out by calling printFullHistory()?

void printFullHistory(char** history){
    for(int i = 0; i < sizeof(history); i++){
        for(int j = 0; j < sizeof(history)[i]; j++){
            printf("%s", history[i][j]);
        }
    }
}//end printFullHistory

int main(){
    char* history[10];
    strcpy(history[0], "ls");
    printFullHistory(history);
    return 0;
}//end main
Mitchell Griest
  • 467
  • 1
  • 7
  • 21

2 Answers2

3

sizeof being one of your issues, this is also wrong:

char* history[10];
strcpy(history[0], "ls");

history[0] is not initialized to point to valid memory, you can't write to it.

And besides:

printf("%s", history[i][j]);

history[i][j] refers to j-th letter of i-th string, so maybe you wanted to use %c. Nevertheless, you can't print values of uninitialized variables. If you do, this is undefined behaviour.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
1

Two main problems:

  1. You strcpy() to an uninitialized pointer, that invokes undefined behavior. Your need to make the pointer point to valid memory. Either by using malloc()/free() or by making the array two dimensional.

  2. You are using the sizeof operator to determine the size of an array through a pointer to the array, that's wrong. When the operand of sizeof is a pointer the result if the size of the pointer namely sizeof(void *) which is not the size of the array. You can pass the size to the function or, you can add a NULL pointer at the end of the array and iterate until you find it, just the same concept used for strings in .

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97