将指针数组值复制到C中另一个数组的末尾

时间:2014-11-30 01:44:34

标签: c arrays pointers copy

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

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]);
}    

请帮助我。

2 个答案:

答案 0 :(得分: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); 

答案 1 :(得分:0)

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]);