Array Question
Nov 10, 2015 at 7:51pm UTC
I feel like i've asked this question 10 times and I still don't understand it.
I have code that puts the alphabet into an array.
1 2 3 4 5 6 7 8 9 10
void alphabet()
{
char letter = 'A' ;
char alphabet[26];
for (int i = 0; i < 26; i++) {
alphabet[i] = i + letter;
}
it seems like a for loop is like vegas, what happens in a for loop, stays in a for loop.
I want to take this array and then play with it outside of the function in my main() block. This is more of a philosophical question.
what am i missing here?
Nov 10, 2015 at 7:58pm UTC
Your declaring alphabet inside a function, therefore when the function terminates, alphabet is lost.
1 2 3 4 5 6 7 8 9 10 11 12 13
void getLetters (void );
char alphabet [26];
int main (void ) {
getLetters ();
return 0;
}
void getLetters () {
// Your code minus array declaration
}
You could also declare alphabet in main and pass it as a parameter to getLetters.
Nov 10, 2015 at 9:07pm UTC
if i pass it as an argument, that just means its a declaration right?
I would still need to be able to use the array once its filled. I'm actually trying to take the array I have filled in my alphabet() function and use the array it creates in another function.
but more importantly, i'm struggling to understand how to fill the array in a function and use the array in main.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
void alphabet();
int main()
{
// play with
// alphabet[]
// here
}
void alphabet() {
//code here to
// fill array
alphabet[] // is now filled
}
Nov 10, 2015 at 10:17pm UTC
Method 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
using namespace std;
void fillArray ( char []);
int main() {
char letters [26];
fillArray ( &letters [0] );
}
void fillArray( char letters [] ) {
for (int cnt = 0; cnt < 26; cnt++ )
letters [cnt] = cnt + 'A' ;
}
Method 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
using namespace std;
char *fillArray ();
int main() {
char *alphabet;
alphabet = fillArray ();
cout << alphabet << endl;
delete alphabet;
}
char *fillArray() {
char *alphabet = new char [26];
for (int cnt = 0; cnt < 26; cnt++ )
alphabet [cnt] = cnt + 'A' ;
alphabet [26] = '\0' ;
return alphabet;
}
Nov 12, 2015 at 8:23pm UTC
Conor Bless you ShiftLeft.
I didn't even think about calling the memory space instead of the variable.
Both examples I will hold onto for a long time. thanks
Topic archived. No new replies allowed.