How do I declare a pointer to a character array in C?
I guess I'll give this answer in parts:
Here's a pointer to an array of
char
s (I assumed a 10-element array):char (*x)[10];
Let's break it down from the basics:
x
is a pointer:
*x
to an array:
(*x)[10]
of
char
s:char (*x)[10]
However, most of the time you don't really want a pointer to an array, you want a pointer to the first element of an array. In that case:
char a[10]; char *x = a; char *y = &a[0];
Either
x
ory
are what you're looking for, and are equivalent.Tip: Learn about
cdecl
to make these problems easier on yourself.
You can declare it as extern char (*p)[];
, but it's an incomplete type. This is of course because C has no "array" type generically that is a complete type; only arrays of a specific size are complete types.
The following works:
extern char (*p)[];
char arr[20];
char (*p)[20] = &arr; // complete type now: p points to an array of 20 chars
I could suggest...
Declaration is:
char* array;
And then definition is:
array = "James Bond";
To print out:
printf ("%s \n", array);
Some programmers probably mention the above code isn't memory safe or the definition is actually re assignment, so
char* array = "James Bond";
would be a general practice.
© 2022 - 2024 — McMap. All rights reserved.
int main (int argc, char** argv)
is common in the C (char** argv
is an example of the pointer to the array). – Confessionargv[0] = "main.cpp"
in C language? – Confession