Okay I have been doing a some reading on arrays from both cplusplus.com, and one of Tony Gaddis C++ books.
I thought you could just declare one type of array; however, it turns out
you can also declare an array locally and globally.
My first question is, would this be considered a globally declared array that holds 20 elements or would this be a local array that holds 20 elements?
char books[21];
OR
can I do this
char books[0] = {title, isbn, author};
and just put this before int main(), and call this a globally declared array
kinda of like a function protoype
If its declared outside any function, than it is global.
A global variable (or array) can be called by any function.
If you say char books[0] = {title, isbn, author};
You just made an array of 1 char that's hoolding title,isbn, author (which it doesn't have space for. You can leave the brackets empty and it will take however much space it needs.
Avoid global variables if possible, you CAN do it but I think it's bad practice.
If you don't mind dynamic allocation you could also use:
1 2 3 4 5 6
char **books;
int main(){
books=newchar*[20];
return 0;
}
Note: A char * is a pointer to a string (which is an array of chars), a char ** is a pointer to an array of pointers to strings, a char *** (rarely used), is a pointer to an array of pointers to arrays of pointers to strings (i.e. a matrix of strings).
It sounds a bit confusing but it's something you should understand when dealing with pointers, arrays, and arrays of pointers.
Thank you guys for the explanation, it's interesting.
I started reading about Dynamic allocation in C/C++ and my head started
spinning, is that normal?
Anyhow I will give this a break and hammer on it some more.
And it's good to know that "If its declared outside any function, th[e]n it is global," according to mikeb570.
yea.. you declare an array the same way, whether it's global or local.. what makes an array global or local isn't how it's declared, but where. You should re-read the section on variable scope for a better understanding about that.
And don't mess with dynamic allocation untill you've got a handle on it and feel ready to try it. If done wrong, it could cause problems with your computer. But don't let that scare you from learning how to work with dynamic allocation cause that's a very powerful feature.