+ 1
about strings in c++
Hey, guys Can anyone help me? I can't understand why in this code i have to use &str[2]. How it works? Why if i remove & the compiler gives an error converting char to const char *? and why everything is ok with the &? #include <iostream> #include <string.h> #define size 255 using namespace std; int main() { char *str, *newstr; str= new char[size]; newstr= new char[size]; cout<<"vvedite stroku:"<<endl; cin.getline(str,size); strncpy(newstr,&str[2],5); }
2 odpowiedzi
+ 7
strmcy, copies a character using a pointer, hence `const char*`
When you pass a character into every function, the char will be copied, thus taking some memory.
When a function receives an address (by using &), the char will not be copied. Hence, there will be less memory usage.
Consider the following:
void add(int a, int b) {
// a and b are copies of the original variable
cout << a + b;
}
void add2(const int* a, const int* b) {
// a and b have the same address as the original variables
// The original variables are therefore not copied
cout << *a + *b;
}
int main() {
int v1 = 1;
int v2 = 1;
add(v1, v2);
add2(&v1, &v2);
return 0;
}
----
Which one is more memory efficient? add2 because the local variables, a and b, have the same address as v1 and v2 respectively.
+ 3
Apart from memory efficiency, when you pass `str[2]` you are passing a char rather than a char pointer (which is required by `strncpy` function like Edwin said). Because the function needs a pointer to work; you should pass the address of the char, not the char itself. And that's why you add & operator before `str[2]`, so the function gets the address rather than the char. `&str[2]` means the address of pointer `str` + 2 * sizeof(char).
You can still pass the pointer simply by adding a value to the pointer, like this:
`strncpy(newstr, str + 2, 5);`
And here you don't need the & operator anymore, because this way you are passing the pointer.
Hth, cmiiw