Array access via * and []

I don't think there is a diffence accessing an array element (Correct me if I'm wrong!) with * or [n]? Is it just a choice of preference?

1
2
3
4
5
6
7
8
  char string[] = "This is a string";

  //First element 
  std::cout << *string << std::endl;

  //Same 
  std::cout << string[0] << std:: endl;


Thanks
Last edited on
They are equivalent, but most people will use [] for arrays because it makes it immediately clear you are accessing an array instead of possibly just dereferencing a normal pointer.
Thanks for clearing that up & the link .
In this case it works the same, but there is many other cases where behavior of there operations is completely different.
It is important to save semantic: Do you dereferencing pointer to char which points to desired letter, or you are selecting array element?
Choosing right operator will improve readability and can save you frome some errors.
Example
1
2
3
4
5
char* x = find(someCString, 'a');
std::cout << *x << std::endl; //dereferencing pointer to found character

char* y = newString(oldString);
std::cout << y[0] << std::endl; //Choosing first character of some c-string 
Topic archived. No new replies allowed.