Passing matrix structures to functions

Started by
3 comments, last by spree 19 years, 8 months ago
Hello all. I want to pass a char[2][6] matrix structure to function "print" my functions parameters are "char **", at least I think they should be like that :), now how do I my "str" string matrix to the "print" function from the main func ? #include<iostream> using namespace std; void print(char **s) { cout<<s[0]; cout<<endl; cout<<s[1]; } void main() { char str[2][6]={"Hello","All"}; print(&str[0]); <--- Error }
;)
Advertisement
create your matrix in a different way

like this:

char ** array = new (char*)[2];
for (int a =0; a < 2; a++)
array[a] = new char[6];

strcpy(array[0], "hello");
strcpy(array[1], "All");

then just send in the char ** to your print funciton and it will work
Quote:Original post by Joeman
create your matrix in a different way

like this:

char ** array = new (char*)[2];
for (int a =0; a < 2; a++)
array[a] = new char[6];

strcpy(array[0], "hello");
strcpy(array[1], "All");

then just send in the char ** to your print funciton and it will work


or if you really wonted to do what you was doing then it should be like this:

#include <iostream>void print1(char (*s)[6]) {   std::cout<< s[0] << '\n' << s[1] << '\n'; }void print2(char s[][6]) {   std::cout<< s[0] << '\n' << s[1] << '\n'; }int main() {  char str[2][6]={ "Hello", "All" };  print1(str);  print2(str);   return 0;}


but really in c++ you should use real c++ strings and not use raw arrays but standard library containers, in particular vector being the prefered replacement of raw arrays e.g.:

#include <string>#include <vector>#include <iostream>int main() {   std::vector<std::string> vec_of_strings(2);      vec_of_strings[0] = "Hello";   vec_of_strings[1] = "All";   std::cout << vec_of_strings[0] << '\n';   std::cout << vec_of_strings[1] << std::endl;   return 0;}


or:

#include <string>#include <algorithm>#include <iterator>#include <vector>#include <iostream>int main() {   std::vector<std::string> vec_of_strings;      vec_of_strings.push_back("Hello");   vec_of_strings.push_back("All");   std::copy(vec_of_strings.begin(),             vec_of_strings.end(),             std::ostream_iterator<std::string>(std::cout, "\n"));   return 0;}


EDIT: also main must have a return type of int, main have having a return type void is non-standard.

EDIT2: I know it seems over the top but it really is worth getting into the habbit learn now rather than latter.
Or you could do this instead of using a pointer to a pointer

#include<iostream>using namespace std;void print(char s[][6]){cout<<s[0];cout<<endl;cout<<s[1];}int main(){  char str[2][6]={"Hello","All"};  print(str);}


EDIT: Meh I need to learn how to type faster...[depressed]
Your right, I should go to C++ style
;)

This topic is closed to new replies.

Advertisement