开发者

How to copy char to array of char

I have:

char frame[4][8];
char szBuff[8] = "";
开发者_如何学编程

and I want do something like this:

frame[i][j] = szBuff[0];

but it doesnt work:

Access violation reading location 0xcccccccc.


There are several ways to accomplish what (I presume) you are trying to do. Here are three:

#include <cstring>
using std::memcpy;
using std::memset;

#include <algorithm>
using std::fill;

int main() {
  char frame[4][8];
  char szBuff[8] = "";

  // Method 1
  for(int i = 0; i < 4; ++i) {
    for(int j = 0; j < 8; ++j) {
      frame[i][j] = szBuff[0];
    }
  }

  // Method 2
  memset(&frame[0][0], szBuff[0], sizeof frame);

  // Method 3
  // EDIT: Fix end iterator
  fill(&frame[0][0], &frame[3][7]+1, szBuff[0]);
}


You are reading outside the bounds of your array more than likely. Debug through it and make sure i and j aren't being incremented outside the bounds of the array you declared. Make sure:

i < 4 and i >= 0
j < 8 and j >= 0


Be sure that your i and j are not out of array...

Example:

i = 5;
j = 7;
frame[i][j] = szBuff[0];

Will not work;

This code:

char frame[4][8];
char szBuff[8] = "1";
frame[1][1] = szBuff[0];

Works fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜