snprintf复制2D char数组

时间:2018-04-01 07:13:13

标签: c++ arduino printf c-strings

尝试填充2D char数组。这段代码应该可行:

char FilenamesBuffer[3][64] = {{"test1"},{"test2"},{"test3"}};
char FilenamesBufferTest[3][64] = {{"unwritten1"},{"unwritten2"},{"unwritten3"}};

//print destination buffer before write
for (i = 0; i < 3; i++)
{
  for (j = 0; j < 64; j++)
  {
      Serial.printf("%c", *((char*)FilenamesBufferTest+(i*64) + j));
  }
  Serial.println();
}
Serial.println();

//copying

for (i = 0; i < 3; i++)
{
    Serial.print("copying ");Serial.println(i);
    snprintf(*(FilenamesBufferTest+i*64), 64, "%s", *(FilenamesBuffer+i*64));
}
Serial.println();

//print destination buffer after write
for (i = 0; i < 3; i++)
{
  for (j = 0; j < 64; j++)
  {
      Serial.printf("%c", *((char*)FilenamesBufferTest+(i*64) + j));
  }
  Serial.println();
}

输出:

unwritten1
unwritten2
unwritten3

copying 0
copying 1
copying 2

test1ten1
unwritten2
unwritten3

看起来只复制第一行。我尝试将char数组地址转换为(char**),这似乎不会产生影响。但它打破了这个计划。

snprintf(*((char**)FilenamesBufferTest+i*64), 64, "%s", *((char**)FilenamesBuffer+i*64));

输出:

unwritten1
unwritten2
unwritten3

copying 0

然后很奇怪

snprintf(((char*)FilenamesBufferTest+i*64), 64, "%s", ((char*)FilenamesBuffer+i*64));

作品

1 个答案:

答案 0 :(得分:0)

通过使用指针算法访问数组,你会感到困惑 - 不要这样做;改为使用数组访问。

所以当你这样做时:

*(FilenamesBufferTest+i*64)

FilenamesBufferTest[i*64]不是0时,iFilenamesBufferTest[i]相同。你需要*((char *)FilenamesBufferTest+i*64) ,这将是:

{{1}}

如果确实想要进行显式算术,那就更难了。