【问题标题】:Using memcpy from a pointer to an array从指向数组的指针中使用 memcpy
【发布时间】:2013-10-04 04:21:30
【问题描述】:

我有一个typedef structnamed“项目”,其中包含 2 个char[254](产品名称和公司名称)和 9 个int 变量。 (价格、金额等)。

我从 typedef struct 和一个数组 (1D) 和一个二维数组创建了一个指针。

我已经使用scanf 将数据存储到指针的各个变量中(目前没有问题)。

现在,我想将指针变量的数据“复制并存储”到数组(一维)中,然后将一维数组的数据“复制并存储”到二维数组中。

对于指向一维数组的指针,这就是我所做的:

void pointer_conversion(item *a, item curr[10000], int total)
{
memcpy(&curr[total], a, sizeof(item*));
} 
// Tried doing: memcpy(&curr[total],a,sizeof(item*) * 100); 
// Why 100?= just to be safe.  But still not working.

现在,此函数将指针a 的第一个char[254] 复制并存储到一维数组curr 中,但typedef struct 的其余变量为NULL

有什么建议吗?

(在 Windows 上使用 VS2012)

typedef struct nodebase{
    char productname[254];
    char companyname[254];
    int price;
    int stocks;
//....
    struct nodebase *next; //Use the struct as linked-list
}item;

【问题讨论】:

  • @ZacWrangler 已修复!错字
  • @BeginnerC 现在想想sizeof(item*) 是什么。这不是你想要的。此外,这肯定是重复的。
  • @H2CO3 当我使用typedef struct时是不是一样的?只是问
  • @beginnerC:是的,完全一样:未能为memcpy() 提供正确的大小。

标签: c arrays pointers struct memcpy


【解决方案1】:

考虑代码片段的作用,

  • 函数返回 void/nothing

    void
    
  • 函数名为pointer_conversion,接受三个参数

  • 参数 a 是指向项目的指针,(item*)
  • 参数 curr 是一个项目数组,(item[10000])
  • argument total 是一个 int

    pointer_conversion(item *a, item curr[10000], int total)
    {
    
  • memcpy 采用三个参数,目标、源和要复制的字节数

  • sizeof(item*) 有多大?它和指针一样大。
  • 您要复制多少字节? sizeof(item) 有多大?

    memcpy(&curr[total], a, sizeof(item*));
    }
    
  • 但您可能不想复制 item* 项目的下一个元素

【讨论】:

  • 非常感谢!我被误导了。 ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 2015-06-17
  • 2018-01-04
  • 2020-03-01
  • 2021-02-07
  • 2011-01-27
相关资源
最近更新 更多