#include <stdio.h>
#include <string.h>
int text(char*);
int main()
{
char n[5][100] = {'c'};
char (*p)[100] = n;
text(*p);
return 0;
}
int text(char *p)
{
for(int i = 0; i<5; i++)
{
scanf("%s", p+i);
}
printf("%s", (p+2));
return 0;
}
So I have to print a complete string using pointers fro 2D char array. I declared a 2D array, and declared 2D pointer to it. Then I pass it to function test.
When I print (p+2), I expect it to print the 3rd line. But what it does is it prints the first character of each line from 3rd line to last line, and the whole last line.
What is the mistake?
Your function only takes a single pointer to a
char:char *. When passing the argument to your function, you dereference your 2d array:This means you only pass the first element (in this case the first line).
As
pis a pointer to a singlechar,p+2will just be the third character.What you need to do is to use the correct types:
call it with
Then, in your function, you would write for example
or if you prefer the syntax with pointer arithmetics, this would be