Originally Posted by
0rion
Hmm I'm looking for something to check if my variable is initialised, the function call shouldn't return anything - ie. if the function wasn't completed (doesn't return 0 or NULL or anything) I would print something back.
When you declare a function like
Code:
char* decode_arc4(int* arg1, int arg2);
The function will return a pointer to char. It must return a pointer to char.
Now some C compilers will give a warning if the such a function has a barefoot return statement. (That is a statement return; with no value indicated.) Some C compilers won't even give a warning. Nevertheless, the calling program will always get a value from wherever it expects to get the value from that function. The calling program has no way of knowing whether the called program actually created a valid return value.
Note that C++ compilers will give an error message at compile time, and the compilation will not be successful.
Now, quite often, functions that return a pointer to char are designed so that a return value of 0 is used to indicate something special (like some kind of problem, for example). Since 0 can not be a pointer to anything (that is, it is absolutely guaranteed that C programs can not have access to address 0, this is a reasonable way to give a special message back to the calling program.
Now, here's an example of how such a thing might be put together. I am sure that you can get lots of advice about why it might be better to do something else, But here's an example that you should be able to run.
Code:
#include <stdio.h>
#include <stdlib.h>
char* decode_arc4(int* arg1, int arg2);
int main() {
int int1, int2;
char *save_pointer;
char *msg;
msg = malloc(100);
save_pointer = msg;
int1 = 9999;
for (int2 = 0; int2 < 3; int2++) {
msg = decode_arc4(&int1, int2);
if (msg) {
printf("decode_arc4(&int1, %d) returned: <%s>", int2, msg);
printf(" and int1 = %d\n", int1);
}
else {
printf("decode_arc4(&int1, %d) returned: NULL", int2);
printf(" and int1 = %d\n", int1);
}
}
free(save_pointer);
return 0;
}
char *global1 = "This is message 1";
char *global2 = "This is message 2";
char* decode_arc4(int* arg1, int arg2)
{
char *retval;
if (arg2 == 1) {
*arg1 = 1234;
retval = global1;
}
else if (arg2 == 2) {
*arg1 = 5678;
retval = global2;
}
else {
retval = NULL;
}
return retval;
}
Notice how I retained the value of the pointer that malloc() gave me so that I could free() it before bailing out.
Regards,
Dave