user8993936
user8993936

Reputation:

Segmentation fault from triple char pointer

I have this bit of code that keeps on resulting in a segmentation fault when printing out the 'favorite' books.

void get_favorites(char **titles, int num_books, char ****favorites, int *num_favorites)

int i, current_fav;

printf("Of those %d books, how many do you plan to put on your favorites list?\n", num_books);
scanf("%d", num_favorites);

*favorites = (char ***)malloc(*num_favorites * sizeof(char ***));

printf("Enter the number next to each book title you want on your favorites list:\n");
for (i=0; i < *num_favorites; i++) {
    scanf("%d", &current_fav);
    *(favorites +i)=((&titles)+(current_fav-1));
}

printf("The books on your favorites list are:\n");
for (i=0; i < *num_favorites; i++) {
    printf("%d.   %s\n", (i+1), ***favorites);
}

I've tried debugging with GDB and for whatever reason, it seems that it can properly retrieve the book string of the first book in char **titles, however when trying to retrieve any of the other books it looks to be a null pointer when triple dereferencing it. I can't figure out why only the first 'favorites' pointer is able to properly dereference down the line, but none more are. Any help is greatly appreciated!

Upvotes: 0

Views: 73

Answers (1)

Barmar
Barmar

Reputation: 781761

char ****favorites should just be char ***favorites. char * is a string, char ** is an array of strings, and char *** is a pointer to the caller's variable that contains the array of strings.

Then you have too many * in your sizeof in the malloc() call. It should always be 1 less than the number of * in the pointer you're assigning. Also, don't cast malloc in C.

*(favorites +i) treats favorites as an array, it's equivalent to favorites[i]. But the array is in *favorites, so you need another level of indirection. Use (*favorites)[i] for this.

((&titles)+(current_fav-1)) is also wrong. *titles is the array of titles, but this is treating titles as the array. This should be (*titles)[current_fav-1].

The loop to print at the end wasn't indexing *favorites at all, it was just printing the first element every time.

void get_favorites(char **titles, int num_books, char ***favorites, int *num_favorites) {

    int i, current_fav;

    printf("Of those %d books, how many do you plan to put on your favorites list?\n", num_books);
    scanf("%d", num_favorites);

    *favorites = malloc(*num_favorites * sizeof(char *));

    printf("Enter the number next to each book title you want on your favorites list:\n");
    for (i=0; i < *num_favorites; i++) {
        scanf("%d", &current_fav);
        (*favorites)[i] = (*titles)[current_fav-1];
    }

    printf("The books on your favorites list are:\n");
    for (i=0; i < *num_favorites; i++) {
        printf("%d.   %s\n", (i+1), (*favorites)[i]);
    }
}

Upvotes: 1

Related Questions