c++ - Passing 2D array and vector of string as argument to function -
i have written 2 function in passing vector of string particular function (printstringvector) print content , in second function, passing array of pointers print content.the first function working fine second 1 giving error below code.
#include <cmath> #include <stdlib.h> #include <cstdio> #include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; int n; void printstringvector(vector<string> & v){ for(int i=0;i<v.size();i++){ cout<<v[i]<<endl;} } void printstringarray(const char *arr[n]){ for(int i=0;i<n;i++){ cout<<arr[i]<<endl;} } int main() { vector<string> vec; cin>>n; const char *arr[n]; for(int i=0;i<n;i++){ string str; cin>>str; vec.push_back(str); arr[i]=str.c_str(); } printstringvector(vec); printstringarray(arr); return 0; }
errors:
vinod@vinod-inspiron-3537:~/documents/hackerrank$ g++ passing_vector_of_string_or_passing_2d_array.cpp passing_vector_of_string_or_passing_2d_array.cpp:17:35: error: expected ‘,’ or ‘...’ before ‘arr’ void printstringarray(const char* arr[n]){ ^ passing_vector_of_string_or_passing_2d_array.cpp: in function ‘void printstringarray(const char*)’: passing_vector_of_string_or_passing_2d_array.cpp:19:33: error: ‘arr’ not declared in scope for(int i=0;i<n;i++){ cout<<arr[i]<<endl;} ^ passing_vector_of_string_or_passing_2d_array.cpp: in function ‘int main()’: passing_vector_of_string_or_passing_2d_array.cpp:40:25: error: cannot convert ‘const char**’ ‘const char*’ argument ‘1’ ‘void printstringarray(const char*)’ printstringarray(arr);
const char *arr[n]
this not valid declaration (unless n
constant expression). c++ has no variable length arrays.
"but works me inside main
!'
that's because g++ implements extension c++. extension not seem compatible c variable-length arrays, , buggy. don't use it.
"but how can have comparable functionality?"
use std::vector
. not use pointers, new[]
, delete[]
unless know extremely why need these low-level primitives.
Comments
Post a Comment