Hello, I'm Duck.

 

During the training, the lecturer said, "Arrays and pointers are the same thing."

What is it? ?

 

So, this time, I would like to create a program that outputs character strings using arrays and pointers.

Similar, but with differences.

Let's get started.

program with arrays

First, I made a program that outputs a string using an array.

In test1, prepare an array of 8 characters as char str[8]; and use strcpy to input and output the string.

Let's run it.

output correctly.

identity of array

I used it casually, but let's take a look at what this array really is.

In this program, as shown in Figure 3, I entered the character "altima" in str[0]-[7].

The final “\0” is null.

See here for null.

If you simply write str as in test1's strcpy and printf, it behaves as a pointer to the beginning of the array.

str was already used as a pointer in printf and strcpy. Then it seems easy to rewrite using pointers.

Are pointers empty?

For the time being, I tried rewriting what was an array into a pointer as it is.

However, when I tried compiling, I got a warning.

It has not been initialized.

Why?

 

In a previous article, I explained how important initialization is.

When writing char str[8]; in the array, a memory area for 8 characters is reserved.

Therefore, the starting address is also known at the time of declaration.

However, in the case of pointers, just writing char *p does not secure the memory area.

In other words, even if you want to enter string data, you don't know where to enter it.

This can lead to serious errors such as overwriting memory in unintended locations.

malloc

That's where we use the malloc function. This function allocates the specified number of memory areas and returns the address.

I'll give you an example

char *p;

p = malloc(8);

As shown in Fig. 7, memory for 8 characters is secured, and its top address is p.

Now let's rewrite the code in test2 using malloc.

Now I was able to print a string using only pointers.

malloc is a very useful function for working with pointers.

Duck C Language Related Articles

Easy-to-understand explanation of the basics of the C language, which is indispensable for embedded systems!

Initial value problem ver.C language
Forgetting initial values can cause trouble! ?

Actually the same person! ? arrays and pointers
Arrays and pointers, use these two that look similar but are different!

malloc ~challenge to the unknown~
Explains how to use memory, which can be said to be a feature of the C language!

Is it unreadable to humans? Binary file mystery
What is in the contents of that file that cannot be read as text! ?