przekazanie tablicy string do funkcji
Ostatnio zmodyfikowano 2016-10-21 10:50
nofrickingway Temat założony przez niniejszego użytkownika |
przekazanie tablicy string do funkcji » 2016-10-21 10:09:38 Witam w jaki sposób przekazać tablice do funkcji?? #include <iostream> const char * choices[] = { "a", "b", "c", "d" };
void print_choices( ??? choices, int i ) { std::cout << choices[ i ]; }
int main() { print_choices( ??? choices[ 1 ] ); }
edit: ok już wiem #include <iostream>
using namespace std;
const char * choices[] = { "a", "b", "c" };
void print_choices( const char ** choices ) { cout << * choices; }
int main() { print_choices( choices + n ); }
|
|
mateczek |
» 2016-10-21 10:50:42 uwaga tak kod wstawiaj w znaczniki [cpp]//tutaj wstawiaj kod[/cpp] 1 wygodniej użyć string i vector miast surowych tablic #include <iostream> #include<vector> using namespace std;
void print_choices( vector < string > & tab, int index ) { cout << tab[ index ] << endl; }
int main() { vector < string > tablica = { "a", "beee", "ce", "de" }; print_choices( tablica, 1 ); }
2 ty posługujesz się pojedynczymi znakami a nie napisami 3 jeśli uprzesz się na tablice znaków to można tak #include <iostream> void print_choices( const char tab[], int i ) { std::cout << tab[ i ]; }
int main() { const char choices[] = { 'a', 'b', 'c', 'd' }; print_choices( choices, 2 ); }
w twoim przypadku gdy tablica jest globalna (nie zalecane) nawet nie musisz jej przeazywać!!! #include <iostream> const char choices[] = { 'a', 'b', 'c', 'd' }; void print_choices( int index ) { std::cout << choices[ index ] << std::endl; }
int main() { print_choices( 2 ); }
|
|
« 1 » |