0

I want to have an array of strings, and something return a random string from that array, so something like this:

 char* initialblow[] = {"hey", "hi", "hello"}; // this might be bigger or smaller
 char* secondblow[] = {"Bob", "Phil", "Sue"}; 
 int length1 = sizeof(initialblow)/sizeof(char); 
 int length2 = sizeof(secondblow)/sizeof(char);

 ...

 return initialblow[rand() % length1] + ", " + secondblow[rand() % length2]

Am I messing something really obvious up? I haven't touched C for a long time and can't figure out the issue.

0

3 Answers 3

3

Instead of

int length1 = sizeof(initialblow)/sizeof(char);

use

int length1 = sizeof(initialblow)/sizeof(*initialblow);

and instead of

return initialblow[rand() % length1] + ", " + secondblow[rand() % length2]

use something like

char out[256];
sprintf(out, "%s,%s", initialblow[rand() % length1], secondblow[rand() % length2]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Nick! I just looked up sprintf() and just so I'm clear, does this mean that if I were to print out, it'd be the string I wanted?
@Nick I'm returning back to this, what if I want to return out? Would I have a function that's something like: char* getOut() { return *out; }, or something else?
3

Your computation of the length is wrong. initialblow is not an array of char but of char*:

int length1 = sizeof(initialblow)/sizeof(*initialblow);

Also, you can't concatenate string like this in C. You have to use strcat to concatenate a string into an existing one. For this either pass an extra char [] parameter and fill it with the result or do some dynamic allocation to return a char*.

1 Comment

I always find it easier to remember sizeof(initialblow)/sizeof(initialblow[0]).
2

You can't initialblow[rand() % length1] + ", " + secondblow[rand() % length2] concatenate like this. What you're doing here is char + char* + char - which is illegal.

initialblow[rand() % length1] is a char

"," is a char*

secondblow[rand() % length2] is a char

If you really want to return a string, then make one (see Nick's answer). However, if you want to return it to the caller, instead of consuming it in the function then you've to go with dynamic memory allocation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.