0

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

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Noah
  • 4,601
  • 9
  • 39
  • 52

1 Answers1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606