简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM