I have a problem building an array of "*" in C++
I have a program that contains the following piece of code for constructing an array of asterisks:
char array[Length][Height];
for (int count开发者_高级运维1 = 1; count1 <= Length; count1++)
{
for (int count2 = 1; count2 <= Height; count2++)
{
strcpy(array[count2][count3], "*");
cout << array[count2][count3];
}
}
cout << endl;
When I attempt to compile the program, I receive the following output:
waves.cpp:48: error: invalid conversion from ‘char’ to ‘char*’
waves.cpp:48: error: initializing argument 1 of ‘char* strcpy(char*, const char*)’
The 'char*' part of the output lead me to do some reading on pointers, and while I understand the basic principle of them, actually implementing them is proving somewhat difficult (and I guess that's the difference between reading about something and doing it).
If someone could tell me where I'm going wrong in this code so I could use it as a worked example, it would go a long way to helping me understand the use of pointers.
Try this:
char array[Length][Height];
for (int count1 = 0; count1 < Length; count1++)
{
for (int count2 = 0; count2 < Height; count2++)
{
array[count1][count2] = '*';
cout << array[count1][count2];
}
}
cout << endl;
Note that your code contained off-by-one errors: count1
and count2
would go from 1 to Length/Height, which would skip the first byte in the array and write one byte past its size. In C/C++, array indices start at zero and end at length - 1. I corrected the errors in the code above.
strcpy()
is intended for copying strings from one place in memory to another. What you want to do is not to copy a string, but to assign a single char value (which, conceptually, is no different from an int apart from its size*). The C language has no native string type -- instead, it uses continuous blocks of memory that end with a byte that has the value zero (null-terminator). Working with strings in this manner is difficult, painful and error-prone. Since your post is tagged with "c++", I would advise you to use the C++ Standard Library's string type when dealing with strings in the future.
* On some platforms, an int might be no larger than a char.
What you have is an array of an array of char
, but you're trying to copy in a char*
instead.
array[count2][count3] = '*';
Use '*'
to enclose the character.
Also, use simple assignment operator =
, for character assignment, as in:
array[count1][count2] = '*';
with the subscripts count1
& count2
running from 0
to Length-1
& Height-1
respectively.
strcpy()
is unneccesary as you are putting together the array character-by-character.
精彩评论