Well, the code is C. I hope nobody minds that considering it's a forum for C++. In any case, it's just standard C, so I
think the same should be applicable in C++.
So... The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
*
*/
int twister(void);
int main(void) {
int *p;
p = twister();
unsigned int i;
for (i=0;i<10;i++) {
printf("%i\n",*p); *p++;
}
return (EXIT_SUCCESS);
}
int twister(void) {
srand(time(0));
static int x[10] = {0};
unsigned int i;
for(i=0;i<10;i++) {
x[i] = rand()%('z'-'a')+'a';
}
return x;
}
|
Ok... It runs good. Gives me 10 random integers between 97 and 122... Before someone points out abundant instances of bad programming practices, please know that I know they exist (abundantly) and gcc warns me about them every time I compile, however it's not my biggest concern right now.
The problem is: I want
twister()
to return
char
instead. However, when I do that, a memory access exception is thrown by my OS, says:
Segmentation fault
...
I tried to go pro and cranked gdb up... It appears that
char *p
cannot acquire return value properly even though the return value has been declared static.
The things which bugs me the most is that it works flawlessly (apparently) with integers! So why problem with characters?
I have frequently noticed character arrays (or C type strings, as I think they are referred to as) being mentioned separately from normal arrays in tutorials, books and articles. Do they behave differently?
And lastly, I am not even sure if that is the right question to ask. I have always had problems with pointers, I have a crystal clear concept tonight and in the morning I wouldn't even be able to justify why I need pointers. There is a string chance I am doing something terribly stupidly wrong. Could anyone point out please?
(And try not to be too blunt, you know, I have feelings... Alright, I don't. :p)