Differences between char * and char [] in C language

Source: Internet
Author: User

It is still very hard to pick up the lost items. Today I found that I don't even know the difference between char * and char.

Many people think that these two definitions have the same effect, but they are actually quite different. Some of my personal opinions are as follows. I hope to correct them if they are incorrect.

Essentially, char * s defines a char pointer. It only knows the memory unit to which it points, and does not know the size of the memory unit. Therefore:
When char * s = "hello";, the value cannot be assigned using the s [0] = 'a'; statement. This will prompt that the memory cannot be "written ".
After char s [] = "hello"; is used, values can be assigned using s [0] = 'a';, which is a regular array operation.
If char s [] = "hello ";
Char * p = s;
You can also use p [0] = 'a'; because this is p = s, all pointer to the array.
The following is another definition:
Char * s = (char *) malloc (n); // where n is the size of the space to be opened
This sentence is actually equivalent:
Char s [n]; defines a pointer to an array to perform subscript operations on the array.

Example

The code is as follows: Copy code

# Include <stdio. h>
 
Int main (int argc, char * argv []) {
Char * buf1 = "this is a test ";
Char buf2 [] = "this is a test ";
Printf ("size of buf1: % d \ n", sizeof (buf1 ));
Printf ("size of buf2: % d \ n", sizeof (buf2 ));
Return 0;
}

The result is:

$>./Main
Size of buf1: 4
Size of buf2: 15

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.