C language programming learning: the difference between using pointers and arrays

In the C language, both pointers and array names represent addresses, but there are big differences between the two. For beginners, you must figure out the difference between the two.

First, let me give a simple example:

char *p1="hello!"; //Define the character pointer p1, and point the pointer p1 to the first address of the string "hello!".

char s[10]="hello!"; //Define the array s and initialize it.

However, if char s[10]; s="hello!"; then an error will be reported, why? The reason is simple, because the array name is constant.

Closer to home, I will now 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 constant and stored in the constant area, but the pointer p points to the first address of the string stored in the constant area. Change the value of the character string in the constant area.

In example 1, char p[]="abcdef", the assignment here is 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. At this time, the value of the string can be modified because the value of the string in the stack area is modified. In addition, the array name p at this time is the first address of "abcdef" in the stack area.

 


In addition, if you want to better improve your programming ability, learn C language and C++ programming! Overtaking in a curve, one step faster! I may be able to help you here~

UP has uploaded some video tutorials on learning C/C++ programming on the homepage. Those who are interested or are learning must go and take a look! It will be helpful to you~

Sharing (source code, actual project video, project notes, basic introductory tutorial)

Welcome partners who change careers and learn programming, use more information to learn and grow faster than thinking about it yourself!

Programming learning:

Programming learning:

Guess you like

Origin blog.csdn.net/weixin_45713725/article/details/115079379