简体   繁体   中英

What is the difference between int a[], int *a1[], and int *a2 in C language?

I'm new to C and I'm learning pointer and array. My professor told me that I can use a pointer as an alternative of an array and vice versa. However, when I was programming, I found that there are some differences in usages between them. For example,

int b[] = {1,2,3}; //I consider b as a pointer point to b[0]
int *ptr=b;
ptr++; //works well and point to 2
b++;  //I suppose it will point to b[1] but it doesn't work :(

This is just an example. I'm so confused about int a[] , int *a1[] , and int *a2 (I know the basic concepts), and how they work in memory model? And what syntaxes (usages?) are allowed for pointer/array? (like the example above)
Thank you~

Well... b is an array. b++ does nothing. It would return an error because you are incrementing to an immutable variable.
So, when you assign the pointer ptr to the array b you are pointing to the memory address of the array and by default ptr will point to the index of zero in the array b (being 1).
Therefore, when you write ptr++ you are increasing the index number by one and ptr will then point to the next index value that b holds in that index(ptr = b(which is also saying ptr = 0), b[0] = 1, ptr++, ptr = 1, b[1] = 2 etc..).
I hope this helps somewhat..

The address of b in int b[] = {1,2,3}; is immutable (ie cannot be changed). Therefore, b++ , etc., is illegal.

int a[] is an array of int s (including just a single int ).

int *a1[] is an array of int * . This can be used for an array of int arrays.

int *a2 is a pointer to int . This can point to a single int or an int array.

the concept of pointers and arrays are more or less the same, but arrays have more constraints. array contain the address of the first element in the memory, but it is const. like any other const variable, you cannot change the value assigned to an array to another array (or another index of same array).

and about syntax, int *a2 is pointing to an int in the memory, doesn't matter just one integer, an element of an array or maybe point to block of memory in heap (that is allocated with malloc )

int a[] is the syntax for an array, an array is a block of memory in stack and cannot be changed or freed or anything, it will be freed at the end of the scope.

the last one int *a1[] is an array type of int* s, this means that it can have elements with type int* , and each int* can point to a block or single integer in memory (4 Byte) or another array or...

you can also read about them here: https://www.geeksforgeeks.org/difference-pointer-array-c/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM