Flower
Flower

Reputation: 401

Copying strings into an array?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STRING_LENGTH 20
#define MAX 30

int read_string(char string[], int n);

int main(){
    int i = 0;
    char *name_list[MAX];
    char word[STRING_LENGTH + 1];

    for (;; i++){
        printf("Enter a word.\n");
        read_string(word, STRING_LENGTH);
        if (word[i] == '\0')
            break;
        name_list[i] = malloc(sizeof(char) * 20);
        strcat(name_list[i], word);

    }


}

int read_string(char string[], int n){
    int ch, i = 0;

    while ((ch = getchar()) != '\n')

    if (i < n)
        string[i++] = ch;
    string[i] = '\0';

    return i;
} 

The point of this program is to read in words and place them into an array of pointers for sorting. this is what i have so far, my debugger is saying that the use of strcat is unsafe but I do not know why. It says to use strcat_s but that crashes my program. Any help on how to get this working?

Upvotes: 1

Views: 84

Answers (2)

Valentin Duboscq
Valentin Duboscq

Reputation: 978

Use the memcpy() function :

void *memcpy(void *str1, const void *str2, size_t n)

or the strcpy() function :

char *strcpy(char *dest, const char *src)

Upvotes: 1

moffeltje
moffeltje

Reputation: 4658

Ok, I tested your code and I came to the following final code that is working for me and does not give me a warning when compiled with -Wall.

Since you are using strcat instead of strcpy, the string stored in words gets added to the data in the array name_list. But because you didn't put all values in that array to 0, it could happen some garbage data is stored in name_list[i] and the words string gets concatenated after that garbage data.

Therefore I used calloc so all values in the memory you allocate are zero. Another way is to just keep malloc but then change strcat() in strcpy().

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STRING_LENGTH 20
#define MAX 30

int read_string(char string[], int n);

int main(){
    int i;
    char *name_list[MAX];
    char word[STRING_LENGTH + 1];

    for (i = 0; i < MAX; i++){
        printf("\nEnter a word.\n");
        read_string(word, STRING_LENGTH);
        printf("\nword%d=%s", i, word);
        if (strcmp(word, "") == 0)
            break;
        name_list[i] = calloc(STRING_LENGTH + 1, 1);
        strcat(name_list[i], word);
        printf("\nname_list[%d] = %s", i, name_list[i]);

    }
    return 0;

}

int read_string(char string[], int n){
    int ch, i = 0;

    while ((ch = getchar()) != '\n')

    if (i < n)
        string[i++] = ch;
    string[i] = '\0';

    return i;
} 

Upvotes: 1

Related Questions