This page was last updated on March 13th, 2020(UTC) and it is currently December 1st, 2020(UTC).
That means this page is 263 days, 5 hours, 22 minutes and 10 seconds old. Please keep that in mind.

37 - Arrays If you played around with the types like you should have, you would know that you can't declare and initialize a char using quotation marks. If you were more studious, you would've found out you can use apostrophes. However, how would you store a large number of chars, instead of always using quotation marks? Like, what if you wanted user input? The C++ string class is pretty cool, but it's not C friendly. I reommend looking it up, but, for now, we'll use the c-style method since it's good enough.

#include <stdio.h> //------------------------------------------------------------------------ extern "C" int rand(); //stdlib.h, but djgpp is kinda broken out of the box. extern "C" void srand(unsigned int seed); //Same as above. extern "C" int time(int *junk); //time.h, but likely broken. //------------------------------------------------------------------------ extern "C" void meow(){ srand(time(0)); //Checks for null pointer, which is fine. char name[1024]; //Yeah, I doubt his name's longer than a kilobyte. int lucky[]= {rand(), rand(), rand(), rand()}; printf("Give me your name: "); fgets(name, 1024, stdin); //Please do not use gets. for(int i = 0; i < 1024; i++) if(name[i] == '\n'){ name[i] = 0; break; } printf("Your name is %s.\n", name); //For the love of God, never let user input to become the format string. for(int i = 0; true; i++){ if(name[i] == 0) break; printf("'%c' = 0x%02x\n", name[i], (int)name[i]); //Caste is for safety on passing correct data size. } printf("Your lucky numbers are %i, %i, %i, and %i\n", lucky[0], lucky[1], lucky[2], lucky[3]); }

rand() needs a seed, which we can set with srand(), and time() is a fair seed. I wouldn't use rand() for more than just a video game or for some testing. It's not really random, but it's close enough for these purposes. Notice that these are offsets in the square brackets, but not in the form of bytes, but offset*sizeof(). Also, the name without brackets is a pointer to the first element. This is why you'll see some functions saying char*, because they're expecting a char* to point to a consecutive list of characters terminated by a null character. Square brakets may only be empty when initializing. Also, it's possible to have "multidimensional arrays" meaning you can have an array of char* (char**), but usually you don't see that unless there's an acompanying int (main's proper declaration is "int main(int argc, char** argv)" which is how you get your command line parameters if we weren't using assembly for our main [now you can do it without using an assembly source]).

Get your own web kitty here!
┬ęCopyright 2010-2020. All rights reserved.