I have written two function in which I am passing vector of string to a particular function (PrintStringVector) just to print content and in second function, passing the array of pointers to print the content.The first function is working fine but second one is giving error which is below the my 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’ was not declared in this 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**’ to ‘const char*’ for argument ‘1’ to ‘void PrintStringArray(const char*)’
PrintStringArray(arr);
strwhen you doarr[i] = str.c_str();This will lead to undefined behavior.c_str()returns back a pointer that is C compatible, but this pointer is only valid while thestd::stringobject that returned it exists. You are using it after this point.