Easy tutorial for C / C ++ - string 4
(Two-dimensional
arrays and pointer to string arrays)
- Learn how to store multiple strings. You can define
multiple one-dimensional arrays and save them as different array names. And you
can also use a two-dimensional array to store multiple strings. Let's look at
how to store strings using a two-dimensional array.
- In a two-dimensional array, rows can be represented by
the number of strings to be stored, and columns by one greater than the length
of the longest string (including the null character).
- Let's look at it in two ways: a two-dimensional array
and a pointer to string array.
Example Code
#include
<iostream>
#include
<string.h>
using
namespace std;
int
main() {
char st1[3][10] = { "black",
"blue",
"orange" };
cout << " Print \'st1[3][10]\'
" << endl ;
for(int i=0; i<3; i++){
cout << "st1[" << i
<< "] = " << st1[i] <<endl;
}
cout << endl ;
char *st2[3] = { "white",
"red",
"pink" };
cout << " Print \'*st2[3]\'
" << endl ;
for(int i=0; i<3; i++){
cout << "st2[" << i
<< "] = " << st2[i] <<endl;
}
cout << endl ;
for(int i=0; i<3; i++){
cout << "*st2[" << i
<< "] = " << *st2[i] <<endl;
}
return 0;
}
- We have defined a two-dimensional array 'st1' to store
strings. To store the three strings 'black, blue, orange', the rows and columns
were set to 3 and 10, respectively. Let's print out the stored strings using
the for loop. If you omit a column in a two-dimensional array and represent
only the row elements, it represents the starting address of the row. We will
print the start address (st1 [i]) of each line after the '<<' operator.
- Defined a pointer array '* st2 [3]' that stores three
character pointers, and gave 'white, red, pink' as initial value. The pointer
to array stores the start address value of each string.
- After the '<<' operator, we represent the
elements of the pointer array (st2 [i]) and output the stored strings. Let's
also print the '*' operator in front of the pointer array element.
results
:
Print
'st1[3][10]'
st1[0]
= black
st1[1]
= blue
st1[2]
= orange
Print '*st2[3]'
st2[0]
= white
st2[1]
= red
st2[2]
= pink
*st2[0]
= w
*st2[1]
= r
*st2[2]
= p
- You can see three strings 'black, blue, orange' as a
result of a two-dimensional array 'st1'.
- As a result of the pointer array 'st2', the string
'white, red, pink' is output.
- Each
element of the pointer to array 'st2' stores the start address value of each
string. You can see that the start (first) value of the string is printed
because the '*' operator is prepended.
No comments:
Post a Comment