alt.126
alt.126

Reputation: 1107

Is * equivalent to [] in C?

Would coding:

char *argv[]

would be the same as:

char **argv

Or would:

char *string1;
int  *int_array;

be exactly the same than:

char string1[];
int  int_array[];

Upvotes: 1

Views: 1023

Answers (4)

Lorhan Sohaky
Lorhan Sohaky

Reputation: 19

No.

The concept of arrays is related to that of pointers. In fact, arrays work very much like pointers to their first elements, and, actually, an array can always be implicitly converted to the pointer of the proper type.

Pointers and arrays support the same set of operations, with the same meaning for both. The main difference being that pointers can be assigned new addresses, while arrays cannot.

Read more at cplusplus.

Upvotes: 1

Lucy Isabelle
Lucy Isabelle

Reputation: 98

No! Well, it depends on the context but explicitly they aren’t the same type.

* is a pointer whereas [] is an array.

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is * before the varname

Where an array is a list of objects.

I recommend looking up what pointers are as they are a strong part of C and C++.

Here is a good place to learn about them https://www.tutorialspoint.com/cprogramming/c_pointers.htm (also the place I got the quote from above)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

There are several contexts where [] could be used. It gets a different treatment depending on the context:

  • Function parameter declaration - here char *argv[] is equivalent to char **argv
  • Array declarations with initialization - here int x[] = {1, 2, 3} is a way to have the compiler count array elements for you
  • Declaration at translation unit scope - here int x[] is treated as a tentative declaration, with storage provided at some other place
  • Last member of a struct - this is a flexible member declaration, which lets you "embed" arrays of variable size into a struct
  • Compound literals - (const int []) {1, 2, 3} lets you construct arrays "on the fly" without declaring a special variable.

As you can see, * and [] get the same treatment only in the first context; in all other contexts the treatment is different.

Upvotes: 3

cadaniluk
cadaniluk

Reputation: 15229

Absolutely not. One is a pointer, the other one is an array.

However, when it comes to parameters, char *param is equivalent to char param[] or char param[16], for example.

From the C11 draft N1570, §6.7.6.3/7:

A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type" [...]

Upvotes: 5

Related Questions