1

In this code I'm generate random number in specific range, but I want the out put of array must be

m1,m1,m3,m1 ..

I mean adding the word "host" to every number that is generate randomly, how can do this please? this is code

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
  int a[50];

  srand(time(NULL));

      a[i] = rand() % (3 + 1 - 1) + 1 ;
      printf( " %d\n", a[i]);

}
3
  • well, check out snprintf(). Commented Dec 19, 2017 at 15:34
  • printf( "host%d\n", a[i]); Commented Dec 19, 2017 at 15:36
  • 2
    'Here I am printing a number. How do I print something else next to the number.' Really? Did you try... just putting that other thing in the printf()? And who is upvoting this, and why? Commented Dec 19, 2017 at 15:40

1 Answer 1

3

In your code, ais an integer array, so it cannot hold a string value anyway.

  • In case, you just want to only print the value, use host in the format string in printf() itself, like

     printf( "No. of random selected node = host%d\n", a[i]);
    
  • In case, you want the value to be generated and used, in some way, take a buffer and use snprint() to populate the content.

     snprint(buf, 8, "host%d", a[i]);
    

    the above will put values like host101, host103 etc. in the buf, as a string. Remember, buf has to be large enough to hold the supplied size (8, in this case.)

    Note: Never use magic numbers like 8 in above code, that's just for illustration, use a MACRO definition, at least.

Sign up to request clarification or add additional context in comments.

1 Comment

Code that does not check the return value from snprintf() is not "more" safe" than simply using sprint(buf, "host%d", a[i]);. snprintf() is trading one problem (buffer overrun) for another (mal-formed string).

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.