1

The question is check whether a particular book is found or not in a list of books. I know how to do directly but need to use pointer. Please help me to debug the second code.

#include <iostream>
#include<string.h>
using namespace std;
int main()
{
    int n,i,c=0;
    char A[10][100],s[10];
    cout<<"Enter no:of books: ";
    cin>>n;
    for(i=0;i<n;i++)
    cin>>A[i];
    cout<<"Enter book you want to search: ";
    cin>>s;
    for(i=0;i<n;i++)
    {
        if(strcmp(A[i],s)==0)
        c++;
    }
    if(c==0)
    cout<<"Not found";
    else
    cout<<"Book found";
}

I want to do this using pointer. Kindly help me

I tried this:

#include <iostream>
#include<string.h>
using namespace std;
int main()
{
    int n,i,c=0;
    char A[10][100],s[10];
    const char *p[10][100];
    cout<<"Enter no:of books: ";
    cin>>n;
    for(i=0;i<n;i++)
    cin>>A[i];
    cout<<"Enter book you want to search: ";
    cin>>s;
    p=&A[0];
    for(i=0;i<n;i++)
    {
        if(strcmp(*p,s)==0)
        c++;
        p++;
    }
    if(c==0)
    cout<<"Not found";
    else
    cout<<"Book found";
}

But not working

Lundin
  • 195,001
  • 40
  • 254
  • 396
Gokul Jayan
  • 21
  • 1
  • 3

1 Answers1

0

Switch from const char *p[10][100]; to char (*p)[100]; will solve the problem:

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    int n,i,c=0;
    char A[10][100],s[10];
    char (*p)[100];

    cout<<"Enter no. of books: ";
    cin>>n;
    for(i=0; i<n; i++) {cout << "Enter book name : "; cin>>A[i];}

    cout<<"Enter book you want to search: ";
    cin>>s;
    p = &A[0];
    for(i=0; i<n; i++)
    {
        if(strcmp(*p,s)==0)
            c++;
        p++;
    }
    if(c==0)
        cout<<"Not found";
    else
        cout<<"Book found";
}

Result :

Enter no. of books: 3
Enter book name : abc
Enter book name : def
Enter book name : ghi
Enter book you want to search: abc
Book found

Why is so?

  • Firstly, char *p[10][100] will declare an array of array of pointers, while char *p[100] only declare an array of pointers.

  • Secondly, char *p[100] declare an array of pointers, while char (p*) [100] declare a pointer to a char[] array. Notice the array of pointers to pointer to array.

Also, see Why is "using namespace std;" considered bad practice?

Related : pointer to array c++

silverfox
  • 1,568
  • 10
  • 27