0

我已将数据按顺序读入 char *buffer。然后我需要将该 *buffer 中的字符串复制到一个多维数组中。

因此缓冲区中的第一个数据将转到 temp_message[0],从缓冲区读取的第二个数据将转到 temp_message[1],依此类推。

字符串/数据的长度是 10....这就是我声明 temp_message[4][10] 的原因

我的代码:

  char temp_message[4][10];
  //receiving....
  for(i=0;i<IR_COM_NUMBER;i++) {
    if (wb_receiver_get_queue_length(receiver[i]) > 0) {

        /* read current packet's data */
        ***const char *buffer = wb_receiver_get_data(receiver[i]);***
        count[i]=0;
        if (message_printed[i] != 1) {
          ***temp_message[i][]=buffer;***
          /* print null-terminated message */
          printf("Communicating: received \"%s\" from receiver %d \n",buffer,i);
          message_printed[i] = 1;
        }
        /* fetch next packet */
        wb_receiver_next_packet(receiver[i]);
        message_printed[i]=3;
      } else {
        count[i]++;
        if (message_printed[i] !=2 && count[i]>20) {
          printf("Communication broken from receiver %d!\n",i);
          message_printed[i] = 2;
        }
      }
  }
4

2 回答 2

1

To specify one of the temp_message arrays a second [] operator is invalid. That is the reason for the compiler error. Use strcpy or memcpy to copy characters from character arrays.

strcpy(temp_message[i], buffer);

strcpy is appropriate here provided the contents of buffer are NULL terminated.

于 2013-03-23T08:30:10.260 回答
1

使用该函数strcpy将字符串复制buffer到您的字符串数组中temp_message

strcpy(temp_message[i], buffer);

我在您的问题中发现了一个可能的陷阱。你写你的字符串/数据的长度是 10 但你考虑到尾随\0吗?

于 2013-03-23T08:32:50.520 回答