【问题标题】:Copy pointer array values to end of another array in C将指针数组值复制到C中另一个数组的末尾
【发布时间】:2014-11-30 01:44:34
【问题描述】:

这就是我想要的。我尝试了很多方法,但都没有成功。我想将第二个数组值复制到第一个数组的末尾。

uint8_t *set = getCharacterPattern('A');
uint8_t *set2 = getCharacterPattern('B');

// Here I want to copy *set2 values to end of *set array

for (uint8_t i=0; i<(getCharacterSize(A)+getCharacterSize('B')); i++){
    setLed(0,i,set[i]);
}    

请帮帮我。

【问题讨论】:

  • 我想知道为什么有人拒绝我的问题...

标签: c arrays pointers copy


【解决方案1】:

您需要为组合数组分配内存并将两个数组复制到新内存中。我假设 getCharacterSize 函数返回相应数组中的元素数。

   // Combine arrays set and set2
   int sizeA = getCharacterSize('A');
   int sizeB = getCharacterSize('B');
   int sizeBoth = sizeA + sizeB;
   uint8_t *bothSets = malloc(sizeBoth * sizeof uint8_t);        
   memcpy(bothSets, set, sizeA * sizeof uint8_t);
   memcpy(bothSets+sizeA, set2, sizeB * sizeof uint8_t);

   // Use combined array
   for (uint8_t i=0; i<sizeBoth; i++){
     setLed(0, i, bothSets[i]);
   }

   // Release allocated memory
   free(bothSets); 

【讨论】:

  • newdelete 关键字是 C++ 的一部分,而不是 C。
  • 除非您使用 C++ 编译器进行编译,否则您不想在 C 程序中强制转换 malloc() 的结果:stackoverflow.com/questions/605845/…
  • 很抱歉吹毛求疵,但 C++ 不是 C,这些细节真的很重要。
  • @AlexReynolds,我同意,细节很重要。感谢您纠正我。
【解决方案2】:
int len = getCharacterSize('A');
int len2 = getCharacterSize('B');
for (int i=0; i<len+len2; i++)
    setLed(0,i,i<len ? set[i] : set2[i-len]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多