Sep 1, 2013 at 2:23pm UTC
what is wrong here? i am trying to assign hii to second row of array!
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
using namespace std;
int main()
{
char a[2][5];
*(a+1)="hii" ;
//cout<< a[1]<<endl;
return 0;
}
Last edited on Sep 1, 2013 at 2:54pm UTC
Sep 1, 2013 at 4:35pm UTC
@hellcoder
When you declare a[2][5] you are declaring an array with 2 elems each of which is an array of 5 chars.
With a char array you have to copy the data in, using strcpy (or equivalent.)
1 2
char a[5];
strcpy(a, "Hi!" );
The same rules apply here:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
using namespace std;
int main()
{
char a[2][5];
strcpy(a[1], "hi!" ); // copy "hi!" into second buffer in array
cout<< a[1] <<endl;
return 0;
}
I altered *(a+1) to a[1] as I think it reads more clearly, esp. when dealing with arrays.
Chriscp has replaced your 1D array of char buffers with a 2D array of std::string elements.
Did you want a 1D array? Or a 2D array??
Andy
Last edited on Sep 1, 2013 at 4:52pm UTC
Sep 1, 2013 at 5:07pm UTC
@lumpkin that is the same thing! both ain't works
Last edited on Sep 1, 2013 at 5:43pm UTC
Sep 1, 2013 at 5:20pm UTC
hellcoder wrote:ain't works
Can you please explain?
Last edited on Sep 1, 2013 at 5:20pm UTC
Sep 1, 2013 at 5:45pm UTC
@andy
2-D array!
n thanks!
Sep 1, 2013 at 5:47pm UTC
@Chriscpp
that is not working!
Sep 1, 2013 at 5:54pm UTC
@hellcoder
@Chriscpp
that is not working!
He made a typo. Should be
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
int main()
{
std::string a[2];
a[1] = "hii" ;
std::cout << a[1] << std::endl;
return 0;
}
Last edited on Sep 1, 2013 at 5:55pm UTC
Sep 1, 2013 at 6:10pm UTC
@Chriscpp
vlad it works for me even this
Yes it can work but you complicated the code. It can be written more simpler as I showed. Your code does not correspond to the original declaration of the array as
char a[2][5];
This array is designed to store two character strings. So the more or less equivalent code will be
std::string a[2];
Last edited on Sep 1, 2013 at 6:10pm UTC
Sep 1, 2013 at 6:11pm UTC
Yeah but [0][0->4] are undefinied , [1][0] undeifined , and [1][3&4] are undefined but your example should help them out.
Curious as to why you choose those ones I would of just did something like
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
int main()
{
std::string s_2d_array[ 1 ][ 2 ] = { "hello" , "hii" };
s_2d_array[ 0 ][ 0 ] = "hii" ;
s_2d_array[ 0 ][ 1 ] = "hello" ;
std::cout << s_2d_array[ 0 ][ 0 ] << std::endl;
std::cout << s_2d_array[ 0 ][ 1 ] << std::endl;
return ( 0 );
}
*edit had a typo.
Last edited on Sep 1, 2013 at 6:11pm UTC