Anagram test using C++ having compile time error

62 views Asked by At

Please help me to find out the reason for given compilation errors. If you think there is something wrong then please suggest it to me, as I'm new to programming.

Compilation error:

[Error] request for member 'size' in 'a', which is of non-class type 'char [10]'
[Error] request for member 'size' in 'b', which is of non-class type 'char [10]'

my code is:

#include<iostream>
#include<string>

using namespace std;

int m,n;

void swap(int* p,int* q)//swap
{
    int temp = *p;
    *p=*q;
    *q=temp;
}

int partition(char a[],int l,int h)//partition
{
    int pivot=a[h];
    int index=l;
    for(int i=l;i++;i<h)
    {
        if(a[i]<pivot)
        {
            swap(a[i],a[index]);
            index++;
        }
    }
    swap(a[h],a[index]);
    return(index);
}

void quick_sort(char a[],int l,int h)//sorting
{
    while(l<h)
    {
      int p_index;
      p_index=partition(a,l,h);
      quick_sort(a,p_index + 1,h);
      quick_sort(a,l,p_index - 1);
   }
}


void anargram(char a[],char b[])
{

    quick_sort(a,0,m);
    quick_sort(b,0,n);

    if(m==n)
    {
        for(int k=0;k<m;k++)
        {
            if(a[k]!=b[k])
            {
                cout<<"NO\n";
            }

        }
        cout<<"YES\n";
    }
    else
    {
        cout<<"NO\n";;
    }
}

int main()
{
    cout<<"enter the strings";
    char a[10],b[10];

        cin>>a;
        cin>>b;

    m = strlen(a);
    n= strlen(b);
    anargram(a,b);

    return 0;
}
1

There are 1 answers

11
πάντα ῥεῖ On

C-style arrays don't provide any member functions, as these are primitive types (hence the compiler error).

For such an array you can use sizeof(a) to determine it's actual size within the same scope of it's declaration though. As soon it's decayed to a pointer, you cannot determine the actual size from it.


As yours are most probably used to represent C-style NUL terminated strings, and you probably want to use their actual size from the input, you can also use

char a[10],b[10];

cin>>a;
cin>>b;

m = strlen(a);
n= strlen(b);

I'd recommend rather to use

std::string a(10,0),b(10,0); 

instead.