character string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>


int main()
{
    char* mx = "whatis" ;
    
    for (int i  = 0; i<7; i++) {
        printf("\n%c",mx[i]);
    }
    printf("%lu",sizeof(mx));


    
    for (int i  = 0; i<6; i++) {
        printf("\n%c",mx[i]);
    }
    printf("%lu",sizeof(mx));

}



http://coliru.stacked-crooked.com/a/c5174e57f7ecab19

q1)Can I know what is happening inside this code that is making it not able to display garbage at the end of the first loop but simply move to the next line
and display the sizeof(mx)

q2)c is not very good at keeping track of how long arrays are,does the same apply for c++ or is it compiler specific?
I was playing with it and something is messed up with your "printf" command it was messing up some of my code I put into it. Also it didn't look like sizeof() was working right ether but I could be wrong.. and I'm sure I wasn't using it right. I've never learned them functions..

my C++ code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
//using namespace std;

int main()
{
	std::string name = "MATTHEW";

	for (int i = 0; i != name.size(); ++i)
	{
		std::cout << name[i] << std::endl;
	}
	std::cout << "Size of string is: " << name.size() << std::endl;

	//system("PAUSE");
	return 0;
}
Last edited on
sizeof(mx) has nothing to do with my questions ,as it will always print 8 in case of a 64bit machine and 4 in case of a 32 bit machine .
printf is c language equivalent of cout.

Here is the kindof pure c++ code but my questions remain the same ..

http://coliru.stacked-crooked.com/a/372cc9b14d99bf40

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    char* mx = "whatis" ;
    
    for (int i  = 0; i<7; i++) {
       std::cout<<"\n"<<mx[i];
    }
    std::cout<<sizeof(mx);
    
    for (int i  = 0; i<6; i++) {
        std::cout<<"\n"<<mx[i];
    }
    std::cout<<sizeof(mx);

}




Last edited on
any clues anybody ?
mx[6] is not '\n'
i think by mx[6] you are accessing to memory which is not for mx.

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
    char* mx = "whatis" ;
    
    if(mx[6] == '\n') std::cout << "has new line char";
    else std::cout << "not";

}
@anup30 ahh mx[6] should or shouldnot be a null termination ?

edit : it is part of the mx as it is a null termination character

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
    char* mx = "whatis" ;
    
    if(mx[6] == NULL) std::cout << "YES";
    else std::cout << "not";

}
Last edited on
still both my questions are unanswered
Topic archived. No new replies allowed.