char* and char[] usage in C language-analysis _c language

Source: Internet
Author: User

The difference between char* and Char [] in C language is analyzed in this paper. Share for everyone to use for reference. The specific analysis is as follows:

In general, many people will feel that these two definitions of the same effect, in fact, the difference is very large. Here are some of the personal observations that have been wrong.

In essence, char *s defines a pointer to a char that only knows the unit of memory to which it is pointing, and does not know how large the memory unit is, so:

When char *s = "Hello", the s[0]= ' a '; statement cannot be used to assign values. This will prompt the memory not to be "written".

When "Hello" is used with char s[]=, it is entirely possible to use s[0]= ' a '; assignment, which is a normal array operation.

If defined:

Char s[] = "Hello";
char *p = s;

You can also use p[0] = ' a '; because this is P ==s, it's a pointer to an array.

Here's another definition:

Char *s = (char *) malloc (n (www.jb51.net));//where n is the size of the space to be opened

This sentence actually corresponds to:

Char S[n];

is also defined as a pointer to an array that can be used for subscript operations of an array

Example

#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:

$ >/main
Size of Buf1:4
Size of Buf2:15

I believe that this article on the C language Program design learning has a certain reference value.

Related Article

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.