Reputation: 43
#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?
Upvotes: 0
Views: 1096
Reputation:
Your function only takes a single pointer to a char
: char *
. When passing the argument to your function, you dereference your 2d array:
text(*p);
This means you only pass the first element (in this case the first line).
As p
is a pointer to a single char
, p+2
will just be the third character.
What you need to do is to use the correct types:
int text(char (*p)[100]);
call it with
text(p); // <- no dereference!
Then, in your function, you would write for example
printf("%s", p[2]);
or if you prefer the syntax with pointer arithmetics, this would be
printf("%s", *(p+2));
Upvotes: 2