0
#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?

1
  • 1
    The function int text(char*); does not accept a pointer to a 2D array. It accepts a pointer to first character of a one-dimensional array. Commented Nov 21, 2017 at 15:25

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.