Trying to understand pointers and arrays

Possible duplicate:
What is the difference between char s [] and char * s in C?

I was wondering what is the difference between

char *p1 = "some string";

and

char p2[] = "some string";

in terms of memory, can't they be treated the same?

eg.

void foo(char *p);

...

foo(p1);
foo(p2);
+3
source share
7 answers

Everything is explained here: http://c-faq.com/aryptr/aryptr2.html

+4
source

p1 is a pointer, so you can do pointer arithmetic, like p1 ++

P2 is an array of fixed length. you can do sizeof (p2) and it will return 12 You cannot do p2 ++ ie, pointer arithmetic.

0
source

" " p1 . p1 .

p2 " ". , p2. ,

p2 = "a new string" ;

- undefined C. p2 ( , C), ( char).

( 6.3.2.1, . 3) " , sizeof , , , , " " '' , lvalue."

0
char *p1 = "some string";

char . 4 ( ). . :

char const *p1 = "some string";

.

char p2[] = "some string";

12 ( nul) . 12 . , , , char *.

:

p1 = new char[50];  // legal
p2 = new char[50];  // illegal

p1[2] = 'a';  // illegal
p2[2] = 'a';  // legal

:

char const *p1;  // this is what p1 is
char *const p2;  // this is what p2 degrades to. It is a const pointer to the first element.
0

, .

char p2[] = "some string";

12 p2. :

char *p1 = "some string";

, p1, . p1 12 . , p1 .

0

,...

char* p1 = "some string";

... p - , char*. , char char -. - , : -).

, , const pointee, ...

char const* p2 = "some string";

, , Undefined . ++ p1 C. ++, , , , p2 .

p2 const, , . , char - .

, 4 8 .

,...

char a[] = "some string";

... a - , , -. char . sizeof(a) , a 12 , 11 .

C ++, a, , , , . C . ++ , .

, ...

sizeof(a)/sizeof(*a)

, a , .

, , , .

C , , ( ).

++ , , ...

typedef ptrdiff_t Size;

template< class T, Size N >
Size countOf( T const (&)[N] ) { return N; }

countOf , .

++ startOf endOf, . , , , . Wordpress, , , , ( , !:-)).

++ , C .

, std::vector " ".

std::vector, , , , .

hth.,

- Alf

0
source

p1- pointer. p2is an array that calculates a pointer when used in expressions.

Perhaps the analogy has the order:

int x1 = 5;
char x2 = 5;

x1- it is int. x2is that charwhich is evaluated as intwhen used in expressions.

In both cases, the differences become apparent when you try to save something in objects and when you apply an operator to them sizeof.

0
source

Source: https://habr.com/ru/post/1768726/


All Articles