Hi!
how do I send this array to a function to determin wich of
the texts who contains most characters
int main(){
char text[4][20] =
{
"hello",
"hello 2",
"hello 2 u",
"hello 2 u 2"
};
return 0;
}
Printable View
Hi!
how do I send this array to a function to determin wich of
the texts who contains most characters
int main(){
char text[4][20] =
{
"hello",
"hello 2",
"hello 2 u",
"hello 2 u 2"
};
return 0;
}
You could declare a function:
Or something like that. If the array is constant you could declare it globally so it would be accessible from anywhere - but I expect that it isn;t always the same.Code:int myFunction(char **array)
{
// Do some stuff in here:
if(strcmp(array[0], "hello") == 0)
....
return 9;
}
HD
Ive tryed this now.. but it doesnt work?!
#include <iostream.h>
#include <string.h>
int myFunction(char **array);
int main(){
char text[4][20] =
{
"hello",
"hello 2",
"hello 2 u",
"hello 2 u 2"
};
int a = myFunction(text);
return 0;
}
int myFunction(char **array)
{
// Do some stuff in here:
if(strcmp(array[0], "hello") == 0){
}
return 9;
}
What do you mean "it doesn't work"? When you say that try to give more details.
Are you using the string class - or just the string manipulation routines (strcmp, strcpy etc)? If you're using strings then the array problem is just 1-dimensional as you can declare an array of strings.
I am assuming the problem is with the conversion from char[4][20] to char **..?
Sorry about that - you need to declare the functions as
You have to declare one of the dimensions for the compiler to like it.Code:int myFunction(char array[][20])
HD
Here's correct code:
Here's better code:Code:#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int maxchars(char ** arr, int length);
int main(){
char text[4][20] =
{
"hello",
"hello 2",
"hello 2 u",
"hello 2 u 2"
};
int a = maxchars(text, 4);
return 0;
}
int maxchars(char (*arr)[20], int length)
{
int m = 0, i, l;
for(i=0; i < length; i++) {
l = strlen(arr[i]);
m = max(m, l);
}
return m;
}
The code is better because it uses STL algorithms and the C++ string class.Code:#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class pred_strlen {
public:
bool operator ()(const string &s1, const string &s2) {
return s1.length() < s2.length();
}
};
int main(){
string text[4] = {
string("hello"),
string("hello 2"),
string("hello 2 u"),
string("hello 2 u 2")
};
int a = max_element(text, text+4,
pred_strlen())->length();
return 0;
}
I agree - but I wasn't sure that this was allowed - plus I don't know them very well :rolleyes:
HD
If the question is as you said above, then the code given is about as correct as you can get in C++.
If your teacher complains, as I've said before, send them here :)
OK!!
Thanks for your help...