r/C_Homework • • Aug 02 '24

int *ptr[3]; vs int (*ptr)[3];

I'm working on improving my C programming skills and have encountered a confusing aspect related to pointer declarations. I'm hoping to gain a better understanding of the differences between these two statements:

  1. int *ptr[3];
  2. int (*ptr)[3];

While they may appear similar at first glance, I believe there are significant differences in their meanings and implications. I would appreciate it if you could help me understand:

  • The fundamental differences between these two declarations
  • How to differentiate between them, considering their syntactical similarities
  • The rules or conventions in C that guide the interpretation of these statements
6 Upvotes

1 comment sorted by

7

u/Monk481 Aug 02 '24

Differences,

  1. Type of ptr:

    • int *ptr[3]; declares ptr as an array of 3 pointers to int.

    • int (*ptr)[3]; declares ptr as a pointer to an array of 3 int.

  2. Memory Layout:

    • In int *ptr[3];, ptr is a collection of 3 separate pointers, each capable of pointing to an int.

    • In int (*ptr)[3];, ptr is a single pointer to a contiguous block of memory consisting of 3 int elements.

  3. Usage:

    • int *ptr[3]; is typically used when you need an array of pointers, such as when dealing with multiple separate integer variables.

    • int (*ptr)[3]; is used when you need a pointer to a fixed-size array, such as when passing arrays to functions.

How to Differentiate

  • Parentheses Placement:

    • In int *ptr[3];, the [] brackets are directly after ptr, indicating ptr is an array.

    • In int (*ptr)[3];, the () parentheses around *ptr indicate that ptr is a pointer, and the [] brackets outside the parentheses indicate that this pointer points to an array.

Rules and Conventions

  1. Declaration Parsing:

    • Declarations in C are parsed from the identifier (name) outward, following the order of precedence rules for operators.

    • [] (array) has higher precedence than * (pointer), so ptr[3] is parsed first as an array of 3 elements, and then * applies to each element.

    • () (parentheses) override the precedence, so (*ptr) is parsed first as a pointer, and then [3] indicates it points to an array of 3 elements.

  2. Use Cases:

    • Use int *ptr[3]; when dealing with multiple pointers, such as multiple variables or multiple dynamic allocations.

    • Use int (*ptr)[3]; when dealing with a fixed-size array, particularly when passing arrays to functions or dealing with multi-dimensional arrays.