I have more of a conceptual question now. Let us say I do this:-
char *str[10]; --> create an array of pointers
str[1]= "John";
I thought this would automatically put John at some memory space and
point str[1] to it.
My colleague argues that in flat bed memory this should not be done. A
new should be used to allocate the memory and then point to it. Of
course he didnt do the best job explaining, hence my question to you
guys, if you can shed some more light on this.
After I have read this thread, I created a small test program and
played with that a little bit, And I have some minor questions on it,
using strings is always welcome though.
Here is the code
#include <iostream>
#include <string>
int main()
{
char *str[2];
str[0]="55555";
str[1]="22";
char * p1=0,p2=0; // **
p1 = &(str[0][0]); // **
p2 = &(str[1][0]); // **
std::cout << "Size of char:" << std::endl;
std::cout << sizeof(char) << "byte(s)" << std::endl;
std::cout << p1 << std::endl;
std::cout << p2 << std::endl;
std::cout << '\"' << str[0] << '\"' << " is of " <<
strlen(str[0])*sizeof(char) << " bytes" << std::endl;
std::cout << '\"' << str[1] << '\"' << " is of " <<
strlen(str[1])*sizeof(char) << " bytes" << std::endl;
for(int i=0;i!=strlen(str[0]);++i)
std::cout << &(str[0+i*sizeof(char)]) << std::endl;
return 0;
}
and compiler(g++) gives an error
ptr.cc: In function 'int main()':
ptr.cc:14: error: invalid conversion from 'char*' to 'char'
however I am a bit confused with this, since I thought that I can take
the address of an lvalue, I used p1 = &(str[0][0]);
+ is not str[0][0] a char and lvalue to which I can assign?
+ should not using the address_of operator on it return an address of
a character which may be assigned to a "char *"?
The second question is that commenting the starred lines in the code
in the new version of the code
#include <iostream>
#include <string>
int main()
{
char *str[2];
str[0]="55555";
str[1]="22";
//char * p1=0,p2=0;
//p1 = &(str[0][0]);
//p2 = &(str[1][0]);
std::cout << "Size of char:" << std::endl;
std::cout << sizeof(char) << "byte(s)" << std::endl;
std::cout << &str[0][0] << std::endl;
std::cout << &str[1][0] << std::endl;
std::cout << '\"' << str[0] << '\"' << " is of "
<<strlen(str[0])*sizeof(char) << " bytes" << std::endl;
std::cout << '\"' << str[1] << '\"' <<" is of "<<
strlen(str[1])*sizeof(char) << " bytes" <<std::endl;
for(int i=0;i!=strlen(str[0]);++i)
std::cout << &(str[0+i*sizeof(char)]) << std::endl;
return 0;
}
and output is:
Size of char:
1byte(s)
55555 ###
22 ###
"55555" is of 5 bytes
"22" is of 2 bytes
0xbfd60d1c
0xbfd60d20
0xbfd60d24
0xbfd60d28
0xbfd60d2c
And the last question is that I have an array of pointers to char, how
can I get the start address of each char array that are pointed by the
pointers in the array? This is a bit related to my 1st question where
I thought I can get it with &(str[0][0]), but apparently there is sth
I am missing.
Best,