When int a[3] has been defined, is there any difference between int* b = a and int (*c)[3] = &a

后端 未结 3 1381
小鲜肉
小鲜肉 2021-01-27 07:06

I\'m trying to deepen my understanding on syntax relevant to pointer in C, and I noticed that If I created an array of int first, int(*)[] is a way of giving a poin

3条回答
  •  -上瘾入骨i
    2021-01-27 07:52

    Both b and c point to the same memory but the difference is big:

    1. These are two different types (pointer to int and pointer to an array of 3 ints)
    2. b is dereferenced to a single integer pointed by b while c is dereferenced to an array of 3 ints which means you can assign an integer to *b (*b = 10;) but you can't do the same for c (but only with specified index (*c)[0] = 10)
    3. Pointer arithmetic is also different b + 1 will increase the value of b by sizeof(int) while c + 1 will increase the value of c by 3*sizeof(int)

    If they're different, when should I use one way instead of choosing the other one?

    As any other type in C, it should be used based on your needs and application. Most commonly used is the int *b; option since it gives you more flexibility. With such pointer you can handle array of any size, it is more commonly used and more readable. While pointer to an array binds you to an array of pre-defined size, its syntax is less readable (in my opinion) and thus will be harder to review/debug the code. In my experience I've never seen a production code which uses pointer to an array but this doesn't mean you cannot use it if you find any advantage of it in your application.

提交回复
热议问题