The main difference between using pointers and arrays in C language is that using a pointer array in C Language

Source: Internet
Author: User

The main difference between using pointers and arrays in C language is that using a pointer array in C Language
In C, pointers and array names both represent addresses, but the two are very different. For Beginners, you must find out the differences between them.

First, let me give a simple example:

Char * p1 = "hello! "; // Defines the struct pointer p1, and points the pointer p1 to the string" hello !" .

Char s [10] = "hello! "; // Defines the array s and assigns its initialization value.

However, if char s [10]; s = "hello! "; In this case, an error is reported. Why? The reason is simple, because the array name is a constant.

Now, let me give two simple examples:

Example 1

Void main ()

{

Char p [] = "abcdef ";

P [0] = 'y ';

Printf ("% s", p );

}

Output Ybcdef in this program

Example 2

Void main ()

{

Char * p = "abcdef ";

P [0] = 'y ';

Printf ("% s", p );

}

This program throws an exception. Why?

In Example 2, char * p = "abcdef", the pointer p is stored in the stack area, but the string is a constant, stored in the constant area, the pointer p points to the first address of the string stored in the constant area. At this time, the value of the string in the constant area cannot be changed.

In example 1, char p [] = "abcdef" is used to copy the string "abcdef" in the constant area to the space of the array p in the stack area. Array p opens up space in the stack area. In this case, the value of the string can be modified because the value of the string in the stack area is modified. In addition, array name p is the first address of "abcdef" in the stack area.

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.