Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

c++ - Difference between [square brackets] and *asterisk

If you write a C++ function like

void readEmStar( int *arrayOfInt )
{
}

vs a C++ function like:

void readEmSquare( int arrayOfInt[] )
{
}

What is the difference between using [square brackets] vs *asterisk, and does anyone have a style guide as to which is preferrable, assuming they are equivalent to the compiler?

For completeness, an example

void readEmStar( int *arrayOfInt, int len )
{
  for( int i = 0 ; i < len; i++ )
    printf( "%d ", arrayOfInt[i] ) ;
  puts("");
}


void readEmSquare( int arrayOfInt[], int len )
{
  for( int i = 0 ; i < len; i++ )
    printf( "%d ", arrayOfInt[i] ) ;
  puts("");
}

int main()
{
  int r[] = { 2, 5, 8, 0, 22, 5 } ;

  readEmStar( r, 6 ) ;
  readEmSquare( r, 6 ) ;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use the type char x[] instead of char *x without initialization, you can consider them the same. You cannot declare a new type as char x[] without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers.

When you use the type char x[] instead of char *x with initialization, they are completely 100% different.


Example of how char x[] is different from char *x:

char sz[] = "hello";
char *p = "hello";

sz is actually an array, not a pointer.

assert(sizeof(sz) == 6);
assert(sizeof(sz) != sizeof(char*)); 
assert(sizeof(p) == sizeof(char*));

Example of how char x[] is the same as char *x:

void test1(char *p)
{
  assert(sizeof(p) == sizeof(char*));
}

void test2(char p[])
{
  assert(sizeof(p) == sizeof(char*));
}

Coding style for passing to functions:

It really doesn't matter which one you do. Some people prefer char x[] because it is clear that you want an array passed in, and not the address of a single element.

Usually this is already clear though because you would have another parameter for the length of the array.


Further reading:

Please see this post entitled Arrays are not the same as pointers!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...