Kent Wong
Kent Wong

Reputation: 143

Copying 1 single character into string

I am trying to create a ASCII table using a customized Abstract data type

typedef struct dictionary {
    int code;
    char* str;
}dictionary;

and I encounter an exception when trying to do the following code

dictionary table[4096];
void preset() {
    for (int i = 0; i < 256; i++) {
        char temp = 0 + i;
        table[i].str = (char *) malloc(sizeof(char));
        strcpy(table[i].str,temp);
    }
}

I don't understand how I access memory wrongly, can someone help ?

Upvotes: 1

Views: 42

Answers (1)

Ctx
Ctx

Reputation: 18420

Three problems:

1) You have to allocate an extra byte for the null terminator of the target string:

table[i].str = malloc(2);

2) You have to pass a pointer to the source to strcpy (this probably caused your segfault):

strcpy(table[i].str,&temp);

3) The source string has to be null terminated, which it isn't in your code. This is not easy to fix directly. But you do not need strcpy() anyway, just set the two bytes directly:

table[i].str[0] = i;
table[i].str[1] = 0;

Then it should work as you expect.

Upvotes: 2

Related Questions