C Warning message

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
I have the following c function that returns a random number between 0 and maxR.

Code:
#include <stdio.h>
char LB_Random(char *maxR,char *dummy)
	{	
	int i;
	static char n[10];
	int rMax = (int)maxR;	
	rMax++;
	srand(time(NULL));
	i = rand() % rMax;
	strcpy(n,(char*)i);
	return n;	
	}

When I compile it it points the return line giving this warning message:

warning C4047: 'return' : 'unsigned char ' differs in levels of indirection from 'unsigned char [10]'

Should I be worried?
 
Yes you should be worried, you're declaring a string and returning the pointer to the string casted to a char.

With maxR being a char* (a string), and you casting maxR to an int, you're effectively getting the address of the string, not the value of maxR's contents, whatever you're putting in maxR (a string, a char?)

Then you're later casting an int to a char* and doing a strcpy on it, which is never actually guarenteed to end.

If maxR is indeed a string, which you wish to interpret as a number, generate a random integer up to that value, and return as a string, the code should be something like :

Code:
char *LB_Random(const char *maxR) {
        static char n[10];
        snprintf(n, 10, "%u", rand() % atoi(maxR));
        return n;
}

atoi() makes an integer from a string, snprintf is like printf but will write to a string instead of a file stream, the 'n' in snprintf means that it is size-limited, it will write a maximum number of characters to the 10-char buffer. 'return n;' will this time return a pointer (char*) rather than a single char.
 
Thanks :p, although I managed to get around it meself. Only a slight difference in code methinks

Code:
#include <stdlib.h>
#include <string.h>
#include <time.h>
char* LB_Random(char *maxR,char *dummy)
	{	
	int i;
	static char n[10];
	int rMax = atoi(maxR);	
	rMax++;
	i = rand() % rMax;
	sprintf(n,"%d",i);
	return n;	
	}
 
Back
Top Bottom