more C pointer confusion

This commit is contained in:
Thomas Bishop 2026-02-08 18:39:09 +00:00
parent 9533468f7d
commit 9dcae3ac16
4 changed files with 79 additions and 0 deletions

View file

@ -80,3 +80,17 @@ The more formal way of doing this would be:
```c ```c
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'} char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'}
``` ```
However, in practice, if you just want quick access to a string, where you don't
need to modify the individual characters later, you can just use a direct
pointer definition:
```c
char *name = "Thomas";
```
And then to use it later just use `name` (no `*`). In this scenario, the string
is a string literal and is stored as read-only. It can be redefined (the pointer
can point to something else) but it's not mutable itself.
More info in [Pointers in C](./Pointers_in_C.md).

0
zk/Impedence.md Normal file
View file

View file

@ -37,3 +37,54 @@ becomes equal to `27`.
Pointers are necessary because C uses a [call by value](./C_is_call_by_value.md) Pointers are necessary because C uses a [call by value](./C_is_call_by_value.md)
system for function arguments. system for function arguments.
## To use a pointer you don't have to declare the value first (confusing)
It is totally legitimate to declare a pointer in one go, especially with
strings:
```c
char *name = "Thomas";
```
Then to reference the value (_not_ the address, the actual value) you just use
`name`.
This is confusing but I just have to accept for now.
Note that if you do this, it creates the string in read-only memory. You can't
modify the individual characters of `"Thomas"`. To do this you would need to
define it as:
```c
char name[] = "Thomas";
name[0] = "t";
```
Here is a real example of me doing this:
```c
void mqtt_publish(esp_mqtt_client_handle_t client, char *topic,
const char *payload)
{
if (MQTT_CONNECTED) {
esp_mqtt_client_publish(client, topic, payload, strlen(payload), 0, 0);
}
}
```
And then when calling the function:
```c
mqtt_publish(mqtt_client, "test_topic", "Test message");
```
Or, using a variable:
```c
static char *topic = "test_topic";
mqtt_publish(mqtt_client, topic, "Test message");
```
> Note in the above the `*` is part of the type definition, _not_ the variable.
> Even more confusing!

View file

@ -5,6 +5,20 @@ tags:
- mqtt - mqtt
--- ---
## Install
```sh
sudo apt install mosquitto
```
This just installs the broker and you can start publishing straight away but if
you want to view the incoming requests to the given topic you need to install
the client package:
```sh
sudo apt install mosquitto-clients
```
## Config ## Config
At `/etc/mosquitto/mosquitto.conf`. At `/etc/mosquitto/mosquitto.conf`.