nice_remark
nice_remark

Reputation: 337

Copy a string from a pointer to an index within an array of pointers

As stated in the title, I wanted to copy a string from a char pointer to location within an array of char pointers. When doing strcpy(), the output results in seg fault, but don't understand why this occurs.

The abbreviated code has the following:

void make_history(char *entry) {
    //static char past_entries[10][10];
    static char *past_entries[10];
    static int index = 0;
    static int array_index = 0;

    char *input;
    if((input = strchr(entry, '\n')) != NULL)
        *input = '\0';

    if(strcmp(entry, "history") != 0) {
        strcpy(past_entries[index], entry);
        *past_entries[index] = &entry;
        index = (index + 1) % 10;
        array_index++;
    }
}

Instead of trying to return a 2d array (which is also very tricky), I thought it would be easier to copy the date from entry to the location within the array of pointers past_entries. Again, strcpy does not work, is there a valid reason as to why this occurs, and a possible workaround or solution to this fix?

Thank you

Upvotes: 0

Views: 296

Answers (1)

Qubit
Qubit

Reputation: 1255

In your example past_entries is just an array of pointers, but you don't allocate any memory to them (initially pointing to NULL). You then try to write to those locations, hence the crash.

To solve this, just allocate some memory before you try to copy your string to it:

past_entries[index] = malloc(strlen(entry) + 1);

Of course you should not forget to free all of this in the end.

Oh and, remove that line: *past_entries[index] = &entry;. It tries to assign a pointer to a character array to a character.

Upvotes: 1

Related Questions