#include<stdio.h>
void display(int n, char *str[])
{
int i=0;
while(i<n) printf("%s ",str[i++]);
}
int main()
{
display(1,"Hello");return 0;
}
when I run this above code I get warnings as
arr.c: In function 'main':
arr.c:11:12: warning: passing argument 2 of 'display' from incompatible pointer
type
display(1,"hello");
^
arr.c:3:6: note: expected 'char **' but argument is of type 'char *'
void display(int n,char *str[])
But then how is it different from
int main(int argc, char * argv[])
And what is the difference between
char **argv and char *argv[]
I am strictly not asking about something like char *argv[100]
As a parameter of a function both char **ptr
and char *ptr[]
are equivalent, otherwise they are different. Former is a pointer to pointer to a char
while latter is an array of pointers to char
.
When a string literal is passed to a function, then pointer to its first character ( char *
type) is passed. You need to change the function's second parameter to char *str
.
void display(int n, char *str)
{
// Function body
}
Well, char **ptr
is a double pointer (pointer to a pointer) of char while char *ptr[]
is an open array of pointer to char.
According to cdel , char **p;
gives the result of "declare p as pointer to pointer to char" while char *p[];
gives "declare p as array of pointer to char."
Character strings are always arrays, and arrays are generally always pointers, so the two are generally equivalent which means that **ptr
= *ptr[]
. What you end up with is an array of an array of chars, or an array of strings. Take main()
for instance:
int main(int argc, char **argv)
{
int i;
for (i = 0; i < argc; i++)
{
if (strcmp(argv[i], "some string") == 0) do something;
}
Do some stuff;
return(0);
}
Another way to declare it is
int main(int argc, char *argv[])
Programmatically, it's easier to understand *ptr[]
than **ptr
.
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.