Difference between char* and char[]

前端 未结 7 1266
清歌不尽
清歌不尽 2020-11-27 03:32

I know this is a very basic question. I am confused as to why and how are the following different.

char str[] = \"Test\";
char *str = \"Test\";
7条回答
  •  孤街浪徒
    2020-11-27 03:43

    A pointer can be re-pointed to something else:

    char foo[] = "foo";
    char bar[] = "bar";
    
    char *str = foo;  // str points to 'f'
    str = bar;        // Now str points to 'b'
    ++str;            // Now str points to 'a'
    

    The last example of incrementing the pointer shows that you can easily iterate over the contents of a string, one element at a time.

提交回复
热议问题