Hello, my name is Duck.
During a training session, I was told by my instructor that "arrays and pointers are the same thing."
What does that mean?
So this time, I would like to create a program that outputs a string using arrays and pointers.
They are similar, but there are some differences.
Let's begin.
Program using arrays
First, let's make a program that outputs a string using an array.
In test1, an 8-character array is prepared with "char str[8];" and "strcpy" is used to input and output strings.
Let's run the program.
The output is correct.
The Identity of Arrays
Let's take a look at the identity of this array, which we have been using without thinking about it.
In this program, as shown in Figure 3, the character "altima" is entered in str[0]~[7].
The last "¥0" is null.
If you simply write "str" as used in "strcpy" and "printf" in test1, it behaves as a pointer to the beginning of an array.
In "printf" and "strcpy", "str" was already used as a pointer. Then it seems easy to rewrite using pointers.
Pointers have no contents?
At first, I tried to rewrite what was an array as a pointer.
However, when I compiled the program, I got a warning message.
It said, "Not initialized.
Why is this?
I mentioned in a previous article that initialization is important.
In an array, when you write "char str[8];", the memory area for 8 characters is allocated.
Therefore, the starting address is also known at the time of declaration.
However, in the case of a pointer, simply writing char *p does not allocate a memory area.
In other words, even if you want to input string data, you do not know where to input it.
This can lead to serious errors, such as rewriting memory in unintended locations.
malloc
This is where the "malloc" function comes in. This function allocates a specified number of memory areas and returns their addresses.
Here is an example
char *p;
p = malloc ( 8 ) ;
This allocates memory for 8 characters as shown in Figure 7, and the first address is "p".
let's rewrite the code for test2 using "malloc".
We can output a string using only a pointer.
So "malloc" is a very useful function for using pointers.
New Engineer's Blush Blog Articles