此C/Arduino代码中发生了什么? [英] What is happening in this C/Arduino code?

查看:107
本文介绍了此C/Arduino代码中发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C和Arduino开发的新手,想知道这里发生了什么.该代码本来可以打印来自HTTP请求的响应,但是它将在大约300个字节后中断.

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

在Javascript中,Ethernet::buffer[off+300] = 0表示您正在将0的值分配给对象或数组中位置[off+300]的某物.为什么要在返回结果之前之前或根本不这样做?

接下来,将Ethernet::buffer的值添加到off的值(这是一个数字)中.因此结果应该是一个数字,但它是一个字符串.

对这里发生的事情有任何见解,我们将不胜感激.谢谢.

来源: EtherCard示例

解决方案

0的分配确保字符串在off之后以300个字符终止.在C和C ++中,基本字符串表示为字符数组,并使用值为0的字符表示字符串的结尾.

例如,这可以防止在控制台上打印过多.

print行上的加法是指针算术,它不是数字"(或者,实际上,它是数字,所有计算机都处理,但是从语义上讲是有区别的).在C(和C ++,在这里)中为字符串的地址添加一个数字可以得到后缀,即它会将那么多字符跳过到字符串中.

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

解决方案

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.

这篇关于此C/Arduino代码中发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆