Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

c++ - Use an array declared inside an if condition elsewhere

I declared an array depending upon a randomly generated number. Now i know we can't use an array generated inside an if block anywhere else but i heared there are ways like dynamic memory allocation & vectors etc? any help on that?

    srand(time(0));
int num=rand() % 6 + 1;

if(num==1)
char word[6] = {'b','a','t','m','a','n'};

if(num==2)
char word[6]={'k','i','l','l','e','r'};

if(num==3)
char word[6]={'b','e','a','u','t','y'};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From what you show, you might use:

srand(time(0)); // Called only once, probably in main

char words[3][6] { // Possibly const // Possibly std::vector<std::string>
    {'b','a','t','m','a','n'},
    {'k','i','l','l','e','r'},
    {'b','e','a','u','t','y'}
};

int num = rand() % 3;
auto& word = words[num]; // char (&word)[6] = words[num];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...