-
Warning from xcode
I am using xcode 3.2.5 and I am reading C++ Without Fear.
At the chapter five there is this code from the author :
Code:
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
//prototypes
int rand_0toN1(int n);
void draw_a_card();
//global declarations
char *suits[4] = {"hearts", "diamonds", "spades", "clubs"};
char *ranks[13] = {"ace", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "jack", "queen", "king"};
int main (int argc, char * const argv[]) {
// insert code here...
int n, i;
srand(time(NULL)); //Set seed for random numbers
while (1) {
cout << "Enter no. of cards to draw (0 to exit): ";
cin >> n;
if (n == 0)
break;
for (i = 1; i <= n; i++)
draw_a_card();
}//end while
return 0;
}//end main
//Draw-a-card function
//Performs one card-draw by getting a random 0-4 and
//a random 0-12.These are then used to index the
//string arrays, ranks and suits
void draw_a_card()
{
int r; //Random index (0 thru 12) into ranks array
int s; //Random index (0 thru 3) into suits array
r = rand_0toN1(13);
s = rand_0toN1(4);
cout << ranks[r] << " of " << suits[s] << endl;
}//end draw_a_card function
//Random 0-to-N1 Function
//Generate a random integer from 0 to N-1
int rand_0toN1(int n)
{
return rand() % n;
}
The two lines after //global declarations give me the following warnings :
Deprecated conversion from string constant to 'char'
Is there something wrong with the code?
The author suggest that this is the proper way to declare arrays of strings.
Thank you.
-
I have xcode 3.1.1 and I get no deprecation warning.
-
Try adding "const" in front of the "char" for both pointer arrays.
-
const worked, but what if you want to change an item?
-
If you want to change an item in the array, don't declare your array as const, and don't initialize the array at compile time, but rather at run time.
Currently, since you are initializing the array at compile time, the compiler treats it as a const and puts (can choose to put) the actual data in read-only memory, so you can't change them at run time.
For this program, having your two arrays declared as const is appropriate, since that data won't change during the course of your program.