Reputation: 21
I am not able to find where it went wrong. When I run the program, it shows "access denied".
#include<stdio.h>
int main()
{
char arr[4][40] =
{ "array of c string",
"is fun to use",
"make sure to properly",
"tell the array size"
};
char *p = arr; /*Char-4-eg-Find-the-output.c:10:11: warning: initialization of 'char *' from
incompatible pointer type 'char (*)[40]' [-Wincompatible-pointer-types]*/
for (int i = 0; i < 100; i++)
{
printf("%c",*p );
p++;
}
return 0;
}
Upvotes: 2
Views: 749
Reputation: 310980
Array designators used in expressions with rare exceptions are converted to pointers to their first elements.
So in this declaration
char *p = arr;
the array designator arr
is converted to a pointer to its first element. Elements of the array arr
have the type char[40]
. So a pointer to an object of this type has the type char( * )[40]
.
However the initialized pointer has the type char *
. And there is no implicit conversion from the type char ( * )[40]
to the type char *
. So the compiler issues a message.
Either you need to use casting like
char *p = ( char * )arr;
or to write
char *p = arr[0];
or
char *p = &arr[0][0];
If you want to output the array of strings as one sentence you could write for example
#include <stdio.h>
int main(void)
{
enum { N = 40 };
char arr[][N] =
{
"array of c string",
"is fun to use",
"make sure to properly",
"tell the array size"
};
for ( char ( *p )[N] = arr; p != arr + sizeof( arr ) / sizeof( *arr ); ++p )
{
if ( p != arr ) putchar( ' ' );
printf( "%s", *p );
}
putchar( '\n' );
return 0;
}
The program output is
array of c string is fun to use make sure to properly tell the array size
Upvotes: 5
Reputation: 791
Change char *p = arr;
to char *p = &arr[0][0];
.
Upvotes: 1