简体   繁体   English

如何使用memcpy将一个字符串复制到另一个字符串(char **)中?

[英]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 ... 我真的不知道正确访问foodComapnies中橙色的第一个单词,第二个单词依此类推...

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. 我想将一些foodComapny写到orange-> foodCompany中,每个foodComapny放在字符串数组的另一个位置。

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

is wrong. 是错的。 sizeof(strlen...) tells you how big a number is - not useful. sizeof(strlen...)告诉您一个数字有多大-没用。

I assume that foodCompanies is an array of names and you want to add foodCompany to that array. 我假设foodCompany是一个名称数组,并且您想将foodCompany添加到该数组。 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 要添加另一个条目,您将需要重新分配或使原始malloc更大

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM