character array printing junk

What am I doing wrong? I thought in both cases some elements of "Phrase" would be printed back, but not so. Trying to dereference the element, but get unwanted characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

int main()

{
	std::cout<<"start"<<std::endl;
	char *array[] = {"Phrase"};
	std::cout<<*array[4]<<std::endl; //deref
	char *argv[] = {"Phrase"};
	cout<<*argv[3];
	return 0;
}


start
‰

Last edited on
Look at the last two compiler warnings:

8:27: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] 
10:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings] 
9:21: warning: 'array[4]' is used uninitialized in this function [-Wuninitialized] 
11:15: warning: 'argv[3]' is used uninitialized in this function [-Wuninitialized]
Note that the subscript operator has higher precedence than the dereference operator so *array[4] will be evaluated as *(array[4]). If you want to access the fifth character of the first element you need use parentheses like this: (*array)[4]
I wonder if you do want an array of c-strings
const char *message = "Phrase";
Or use array syntax
1
2
    std::cout << (*array)[4] << std::endl; 
    std::cout << array[0][4] << std::endl;

1
2
3
4
5
6
std::cout<<"start"<<std::endl;
char *array[] = {"Phrase"};
std::cout<<*(array)[4]<<std::endl;
char *argv[] = {"Phrase"};
std::cout << (*array)[4] << std::endl;
std::cout << array[0][3] << std::endl;


Works fine.

cout<<*(argv[4]); (wrong)
vs.
cout<<(*argv)[4]

I don't want it evaluated as *(array[4])
So where is the output coming from if not the matrix?
Last edited on
some other memory location that has unknown bytes. You can grab a pointer to memory outside of your legit data and if it does not crash, printing it will give you random junk. You can play with it to see...

int main()
{
char * cp;
cout << cp;
return 0;
}
Topic archived. No new replies allowed.