What is happening in this C/Arduino code?

ぃ、小莉子 提交于 2019-12-25 08:07:29

问题


I'm new to C and Arduino development and wondering what's going on here. The code is supposed to print the response from an HTTP request, but instead it cuts off after around 300 bytes.

static void my_callback (byte status, word off, word len) {
  Ethernet::buffer[off+300] = 0; // <--
  Serial.print((const char*) Ethernet::buffer + off); // <--
}

In Javascript, Ethernet::buffer[off+300] = 0 would mean you're assigning a value of 0 to something in an object or array, at position [off+300]. Why is this being done here before the result is returned, or at all?

Next, the value of Ethernet::buffer is added to the value of off (which is a number). So the result should be a number, but instead it's a string.

Any insight into what is going on here would be really appreciated. Thanks.

Source: EtherCard examples


回答1:


The assignment of 0 makes sure the string is terminated at 300 characters after off. In C and C++ basic strings are represented as arrays of characters, and use a character with the value 0 to indicate end of string.

This can be a protection against printing too much on the console, for instance.

The addition on the print line is pointer arithmetic, it's not "a number" (or, under the hood of course it's a number, that's all computers deal with, but semantically there's a difference). Adding a number to the address of a string in C (and C++, here) gets you the suffix, i.e. it skips that many characters into the string.



来源:https://stackoverflow.com/questions/41617239/what-is-happening-in-this-c-arduino-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!