2

希望有人可以在这里帮助我。对 C 语言相当陌生(来自 PHP 背景),几天前就被困在这个问题上。仍在尝试获得头部圆指针等,这是 PHP 所没有的乐趣。

所以基本上,我希望能够将数组中的特定值更新为通过 UART 给出的值。UART 一切正常。只是无法让代码工作以更新数组。来自 UART 的数据将位于下面代码中的字符串“uart”中,并将具有值“0430”(前 2 位是指数组键,第二位是要更新到的值)。

// Array values
int unsigned array[15] = {05,76,33,02,11,07,34,32,65,04,09,32,90,03,44};

// Split the UART string into required parts
// Array Key
int key;
memcpy (key, &uart[0], 2);
// New Value
int value;
memcpy (value, &uart[2], 2);

array[key] = value; // Im sure this is wrong and needs to be done via a pointer?

新数组现在应该是:{05,76,33,02,30,07,34,32,65,04,09,32,90,03,44};

任何建议都会很棒,即使是简短的解释也能很好地帮助我理解。

提前致谢

4

1 回答 1

3

您不能简单地将字符串“04”中的两个字节复制到int变量中并期望它包含 4。您需要将字符串“04”转换为值 4,例如使用atoi

你要这个:

  char uart[] = "0430";   // made up uart buffer just for debugging
  char temp[3] = { 0 };   // buffer for 2 char string, all 3 bytes initialized to 0

  temp[0] = uart[0];
  temp[1] = uart[1];      // temp contains now "04"

  int key = atoi(temp);   // convert from string to integer, key now contains 4

  temp[0] = uart[2];      
  temp[1] = uart[3];      // temp contains now "30"

  int value = atoi(temp); // convert from string to integer, value now contains 30
于 2017-11-22T16:11:31.197 回答