Ilya.K.
Ilya.K.

Reputation: 321

How to copy a string into another string (char **) in a structure with memcpy?

struct orange_t {

    short size;
    Month expirationMonth;
    char** foodCompanies;
    int maxNumberOfFoodCompanies;
    int sellingPrice;
};

memcpy(orange->foodCompanies,foodCompany,sizeof(strlen(foodCompany)));
printf("%s %s",orange->foodCompanies[0],foodCompany);

My problem. that I really don't know to access rightfully to the first word in orange in foodComapnies, the second and so on ...

What is the right syntax and the right way to do it? I want to write a few foodComapny into orange->foodCompanies, each foodComapny in another place in the array of strings.

Upvotes: 0

Views: 204

Answers (1)

pm100
pm100

Reputation: 50190

memcpy(orange->foodCompanies,foodCompany,sizeof(strlen(foodCompany)));

is wrong. sizeof(strlen...) tells you how big a number is - not useful.

I assume that foodCompanies is an array of names and you want to add foodCompany to that array. You dont show how that array was set up (v important). I will assume that its not set up

orange->foodCompanies = malloc(sizeof(char*))// array holds one entry
orange->foodCompanies[0] = strdup(foodCompany); 

to add another entry you will need to realloc or make the original malloc bigger

Upvotes: 1

Related Questions