c++ - 这些指针如何指向不仅仅是一个字符或一个字节?

标签 c++ pointers arduino

<分区>

我是一名高中生,最近使用 Arduino 开始了我的期末考试项目,我试图理解我在使用 VirtualWire 的 radio 发射器示例草图中找到的这段代码。

const char *msg = "hello";
vw_send((byte *)msg, strlen(msg));

我从来没有学过指针甚至 C,所以我在理解它的工作原理时遇到了一些问题。

*msg 是指向 char 的指针,对吧?到那时,它应该是空的,那你为什么可以给它赋值呢?

此外,(byte *)msg 到底是什么鬼东西?这些括号是什么意思?它是一个 byte 等于指针 msg 处的值吗?考虑到它是一个 char,它是如何工作的?为什么有必要?

上下文的完整代码:

// transmitter.pde
//
// Simple example of how to use VirtualWire to transmit messages
// Implements a simplex (one-way) transmitter with an TX-C1 module
//
// See VirtualWire.h for detailed API docs
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2008 Mike McCauley
// $Id: transmitter.pde,v 1.3 2009/03/30 00:07:24 mikem Exp $

#include <VirtualWire.h>

void setup()
{
    Serial.begin(9600);   // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(2000);  // Bits per sec
}

void loop()
{
    const char *msg = "hello";

    digitalWrite(13, true); // Flash a light to show transmitting
    vw_send((byte *)msg, strlen(msg));
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(13, false);
    delay(200);
}

最佳答案

At that point, it should be null, so why can you assign a value to it ?

不,它不是空的。

考虑一下:

int x = 42;

您希望 x 的值为 0 还是 42 ?我假设您会回答 42

那么为什么要假设

const char *msg = "hello";

会导致 msg 为 NULL 吗?它不会。

相反,它被初始化为指向字符串"hello"。或者更准确地说 - 它指向字符串“hello”中的字符 h

另请注意,稍后您可以将指针分配给指向其他一些字符。

例子:

#include <stdio.h>

int main(void) {
    const char* p = "hello";  // Now p points to the 'h' in "hello"
    printf("%s\n", p);
    p = "world";              // Now p points to the 'w' in "world"
    printf("%s\n", p);
    return 0;
}

输出:

hello
world

换句话说,您可以根据需要多次为指针赋予新值。

这是另一个例子:

#include <stdio.h>

int main(void) {
    const char* p = "hello"; // Make p point to the first char in the string
    do
    {
        printf("%s\n", p);
        p = p + 1;         // Make p point to the next char in the string
    } while (*p);

    return 0;
}

输出:

hello
ello
llo
lo
o

关于c++ - 这些指针如何指向不仅仅是一个字符或一个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083429/

相关文章:

c - C 如何检索二维数组的行地址

macos - 如何将青少年板添加到 VS Code 和 Arduino 插件?

c++ - 停止执行而不跳过析构函数

c - 按字符串长度对动态分配的字符串数组进行 Qsort

c - 为什么 char * 和 char 数组在比较中表现不同?

c - nfc.in数据交换 : Status code indicates an error

arduino - 如何为Arduino代码提供条件编译?

c++ - C++ 容器的迭代器失效规则

c++ - 模板中的第二阶段编译

c++ - nasm/yasm 参数,与 C++ 的链接