Character Arrays Subscripting

Pages: 12
1
2
3
4
5
char MyString::strcomp(char string1,char string2) // Compare using Array subscripting
{
    for( int i=0;string1[i]="\0";i++)
        cout<<string1[i];
}


Here's a snippet of code I've been working on for a program. Whenever I run I end up with a "invalid types 'char[int]' for array subscript" error. Could someone please enlighten me where I've gone wrong? Can you not loop through char arrays, or have I misunderstood? Welcome to any feedback.
Last edited on
You can absolutely loop through any array. You've passed string1 as a regular variable, and not an array. Passing an array would be either:

1
2
3
4
5
char MyString::strcomp(char string1[],char string2[]) // Compare using Array subscripting
...
or
...
char MyString::strcomp(char* string1,char* string2) // Compare using Array subscripting 
Last edited on
What you've done is assume that the string type is a null-terminated character array when it's an actual object (non-primitive).

1
2
for (unsigned i = 0; i < string1.length(); ++i) 
 cout << string1[i] << " ";


I do not recommend rcast's method of doing it because I assume you're already working with strings instead of char arrays and you don't want to cast if you don't have too.
Zaita wrote:
I do not recommend rcast's method of doing it because I assume you're already working with strings instead of char arrays and you don't want to cast if you don't have too.


The OP is passing a char not a string Zaita. He even states he is passing char arrays...
Last edited on
@rcast Where does he say he is passing a char?

The error posted is a subscript error that occurs when you try to do a character comparison against a string exceeding it's length. Which occurs in this example because he has assumed a string is null-terminated.
In his post original post he is passing char string1 and char string2. I was guessing that those were C-Strings.

 
char MyString::strcomp(char string1,char string2) // Compare using Array subscripting 


zero117 wrote:

Can you not loop through char arrays, or have I misunderstood? Welcome to any feedback


I'm pretty sure a subscript error can occur with character arrays as well. From what I know anything that is passed with data type char, is a char.
Last edited on
His whole function is messed up :P
Zaita wrote:

His whole function is messed up :P


I believe the MyString::strcomp makes it a method not a function. :p :)
Last edited on
Hmmm true true
Last edited on
Driver file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using std::cout;
using std::endl;

#include "mystring.h"

int main()
{

   char string1[]="I am a very";
   char string2[]="good potato";
   cout<<string1[0];
   char *Ptr1=&string1[0];
   char *Ptr2=&string2[0];


    cout<<"Welcome"<<endl;

    MyString object;

    object.strcomp(*Ptr1,*Ptr1);

return 0;
}


This is in my driver program. I in no way am going to pretend I can fully keep up with arrays involving string literals and even though I have all the proper information actual usage is a bit new to me. As you can see here I was able to declare the strings in one of the accepted formats.

Class Header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using std::cout;
using std::endl;
#include <cstring>
using std::strlen;

class MyString
{

public:

    char strcomp(char string1,char string2) ;
};

#endif // MYSTRING_H 


My problem begins where I leave main and go into the function definitions as presented initially, then I can't seem to make any use of what I've passed in. I included these extra pieces of code so anyone can explain to me if I've done something wrong.
Last edited on
Again let me state my unfamiliarity with these types of arrays. And moreover we were instructed to use array subscripting only for one version of each function, and pointer and pointer arithmetic for another. This is why I'm hesitant to use anything that doesn't have brackets in this particular piece.
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MyString
{

public:

    char strcomp(char* string1,char* string2) ;
};

char MyString::strcomp(char* string1,char* string2) // Compare using Array subscripting
{
	int idx = 0;
	while (string1[idx]) {
        cout<<string1[idx];
		idx++;
	}
	return 'k';
}

int main()
{

   char string1[]="I am a very";
   char string2[]="good potato";
   char *Ptr1=string1;
   char *Ptr2=string2;

    MyString object;

    object.strcomp(Ptr1,Ptr1);

return 0;
}


You have nothing to return yet. If you will be comparing the two as the method name implies than you could return a bool if they are equal or unequal by defining the method as

1
2
3
4
5
6
bool strcomp(char* string1, char* string2) {
if (your compare found the two to be equal) {
   return true
}else{
   return false
}


or if you won't be returning anything

1
2
3
void strcomp(char* string1, char* string2) {
   ...
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void MyString::strcomp(char *string1,char *string2) // Compare using Array subscripting
{

for(int i=0;string1[i]!='\0';i++)// Just to test if string is passed properly
    {
        cout<<string1[i];

    }
    cout<<endl;
   int size1=strlen(string1);
   int size2=strlen(string2);

   int f;

   if(size1>size2)
   {
       f=1;
   }
   else
       if(size1<size2)
       {
           f=-1;
       }
       else if(size1==size2)
       {
           f=0;
       }

   result(f);
}


is what I ended up using. As you can see we are manually recreating the functions that can be found in <cstring> or which ever library the compiler uses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void MyString::result(int x)
{
    if (x==-1)
    {
        cout<<"\nString 1 is less than string 2"<<endl;
    }
    else
        if(x==0)
        {
            cout<<"\nString 1 is equal to string 2"<<endl;
        }
    else
            if(x>0)
            {
                cout<<"\nString 1 is greater than string 2"<<endl;
            }

}

Is the result function the string comparison pointed to.

Again my main difficulty is just to understand what I can and can't do with pointers( ofc besides not going out of the memory address and so forth) . Can I add something into any of my arrays without erasing what was there or are their sizes definitely set? I'm asking since I didn't declare them const.

*
I obviously should change the comment on it since like the original function this one doesn't compare individual characters but rather only the size of the array. However I'll keep it for now to keep track of which function is supposed to stick to subscripts and which is to use pointer arithmetic.
Last edited on
Zaita wrote:
What you've done is assume that the string type is a null-terminated character array when it's an actual object (non-primitive).
You can use the subscript operator with std::string almost like a normal c-string. str[str.size()] should return '\0'.

rcast wrote:
I believe the MyString::strcomp makes it a method not a function. :p :)
In C++ it's often called a member function, so calling it a function make sense.

zero117 wrote:
Can I add something into any of my arrays without erasing what was there or are their sizes definitely set? I'm asking since I didn't declare them const.
The size is fixed and can't be changed. You will find that arrays has a lot of shortcomings which will lead you to learn and love std::vector. All in good time.
Last edited on
Oh, just asking because I have to recreate the connotate function. Well now I'm assuming I'll just have to create a third array to act impartially, or find some way around. And another short coming was I noticed I misunderstood the comp function. I assumed it measured array length and not individual character codes. So now I have it counting if the characters match. If the number of matches is less than the second string it'll return that first is less than the second and so forth.
*Also as you mentioned a friend already told me of the messy business with arrays.
Last edited on
I've gotten much headway and thanks all for any contribution. Can I ask if anyone is familiar with how strcat works? I'm trying to recreate it here, and as said before I don't think I can change the size of string1 to include string 2, probably it uses some hidden coding. The best I've managed is to create a third array of size ( total of length of array 1 and array 2) and then place them in there ( ofc I added two extra spaces, one for a space in between and one for the null character).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

void MyString::Ptrstrcat(char * string1,char * string2)
{
    int val2=strlen(string1);
    int val3=strlen(string2);
    int val1=val2+val3+2;

    char nstring[val1];
    for(int i=0;i<=val1;i++)
    {

            *(nstring+i)=*(string1+i);


    }

    *(nstring+val2)=' ';
    val2+=1;

    for(int i=0;val2<val1;val2++,i++)
    {

            *(nstring+val2)=*(string2+i);

    }
    cout<<"\nTogether both strings are: "<<nstring<<endl;

}


here is one of the functions using the code I described above ( as mentioned earlier I create two, one using regular subscripting, the other using pointer arithmetic) . Again is there anyway to overwrite the value of the first array to include both.

*Edit
Apparently I can assign the value of the new array to array1 by doing
 
string1=nstring;

Last edited on
@rcast yes that is the function, but I'm replicating them, as per our instructions, we are to replicate the compare and concatenate functions that are in the string library. But I'm more fishing for ways how this are done. Again I'm always open to different approaches although I already have my current solution.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void MyString::strncatt(char *string1, char *string2, int d)
{
    int val1=strlen(string1);
    int fin=val1+d+2;

    char farray[fin];

    for(int i=0;i<val1;i++)
    {
        farray[i]=string1[i];
    }

    string1[val1]=' ';

    val1+=1;



    string1=farray;
    cout<<"\nString one is now: "<<string1;
}


Ok I end up running this piece of code because i noticed some odd behaviour. Apparently it automatically fills in the array by combining both of my arrays even though I didn't ask for it. Nor have I manually looped through assigning anything from the second string. Anyone have an explanation as to why this is happening? ( It's not a bad thing per se, but I'd like some closure).

*Tested my previous function doing the same and no sign of this. Is seem to automatically take on the second word from the second string. I'm not sure if this is some kind of memory error.
Last edited on
okay I finished and here's what I have, if someone can tell me why I have errors with the last two functions( they should only be joining the specified numbers or characters) , that would be very nice. Again welcome to any feed back. #include "mystring.h"
.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
void MyString::strcomp(char *string1,char *string2) // Compare using Array subscripting
{
    int size1=strlen(string1);
    int size2=strlen(string2);

    int count=0;//Keeps track of matches

    if( size1<=size2)//Runs if the length of string one is equal to or less than string 2

    {

    for(int i=0;i<size1;i++)

    {
        if(string1[i]==string2[i])
        {
            ++count;
        }
    }

    }

    else
        if(size1>size2)//Runs if the length of the second array is less than the first to ensure program remains in-bounds
        {
            for(int i=0;i<size2;i++)
            {
                if(string1[i]==string2[i])
                {
                    ++count;
                }
            }
        }


      if (count==0)
    {
        result(99);

    }
      else
          if((count>0)&&(count<size2))
          {
              result(-1);
          }
      else
              if(count>size2)
              {
                  result(1);
              }
      else
                  if(count==size2)
                  {
                      result(0);//Calls on function result
                  }


}

void MyString::Ptrstrcomp(char *string1,char*string2)//Compare using Pointer arithmetic
{
    int size1=strlen(string1);
    int size2=strlen(string2);

    int count=0;//Keeps track of matches

    if( size1<=size2)//Runs if the length of string one is equal to or less than string 2

    {

    for(int i=0;i<size1;i++)

    {
        if(*(string1+i)==*(string2+i))
        {
            ++count;
        }
    }

    }

    else
        if(size1>size2)//Runs if the length of the second array is less than the first to ensure program remains bound
        {
            for(int i=0;i<size2;i++)
            {
                if(*(string1+i)==*(string2+i))
                {
                    ++count;
                }
            }
        }


      if (count==0)
    {
        result(99);

    }
      else
          if((count>0)&&(count<size2))
          {
              result(-1);
          }
      else
              if(count>size2)
              {
                  result(1);
              }
      else
                  if(count==size2)
                  {
                      result(0);//Calls on function result
                  }


}


void MyString::strnncomp(char *string1,char *string2,int s)
{
    int count=0;
    for(int i=0;i<s;i++)
    {
        if(string1[i]==string2[i])
        {
            ++count;

        }
    }


      if (count==0)
    {
        result(99);


    }
      else
          if((count>0)&&(count<s))
          {
              result(-1);

          }
      else
              if((string2[s]==' ')||(string2[s]=='\0'))
              {
                  result(1);

              }
      else
                  if(count==s)
                  {
                      result(0);

                  }


}

void MyString::Ptrstrncomp(char* string1,char* string2,int o )
{

    int count=0;
    for(int i=0;i<o;i++)
    {
        if(*(string1+i)==*(string2+i))
        {
            ++count;

        }
    }


      if (count==0)
    {
        result(99);


    }
      else
          if((count>0)&&(count<o))
          {
              result(-1);

          }
      else
              if((*(string2+o)==' ')||(*(string2+o)=='\0'))
              {
                  result(1);

              }
      else
                  if(count==o)
                  {
                      result(0);

                  }

}


void MyString::strcatt(char *string1,char *string2)
{
    int val2=strlen(string1);
    int val3=strlen(string2);
    int val1=val2+val3+2;

    char nstring[val1];
    for(int i=0;i<=val1;i++)
    {

            nstring[i]=string1[i];


    }

    nstring[val2]=' ';
    val2+=1;

    for(int i=0;val2<val1;val2++,i++)
    {

            nstring[val2]=string2[i];

    }

    string1=nstring;
    cout<<"\nTogether both strings are: "<<string1<<endl;

}


void MyString::Ptrstrcat(char * string1,char * string2)
{
    int val2=strlen(string1);
    int val3=strlen(string2);
    int val1=val2+val3+2;//Creates a third array to hold the values of all the array

    char qstring[val1];
    for(int i=0;i<=val1;i++)
    {

            *(qstring+i)=*(string1+i);


    }

    *(qstring+val2)=' ';
    val2+=1;

    for(int i=0;val2<val1;val2++,i++)
    {

            *(qstring+val2)=*(string2+i);

    }

    string1=qstring;
    cout<<"\nTogether both strings are: "<<string1<<endl;

}


void MyString::strncatt(char *string1, char *string2, int d)
{
    int value1=(strlen(string1));
    int value2=(value1+d+2);

    char stringy[value2];

    for( int i=0;i<value1;i++)
    {
        stringy[i]=string1[i];
    }

    stringy[value1]=' ';
    value1=value1+1;

    for(int i=0;i<d;i++)
    {
        stringy[value1]=string2[i];
        value1++;
    }

    string1=stringy;
    cout<<"\nString 1 is now : "<<string1<<endl;
}


void MyString::Ptrstrncat(char * string1, char * string2, int v)
{
    int value1=(strlen(string1));
    int value2=(value1+v+2);

    char stringy[value2];

    for( int i=0;i<value1;i++)
    {
        *(stringy+i)=*(string1+i);
    }

    *(stringy+value1)=' ';
    value1=value1+1;

    for(int i=0;i<v;i++)
    {
        *(stringy+value1)=*(string2+i);
        value1++;
    }

    string1=stringy;
    cout<<"\nString 1 is now : "<<string1<<endl;
}


void MyString::result(int x)
{
    if (x==-1)
    {
        cout<<"\nThe First string almost-fully/barely  matches the second string"<<endl;
    }
    else
        if(x==0)
        {
            cout<<"\nThe First string is equal to the second string"<<endl;
        }
    else
            if((x>=1)&&(x<=2))
            {
                cout<<"\nThe First string is greater than the second string"<<endl;
            }
    else
                if(x==99)
                {
                    cout<<"\nThe strings have no match!"<<endl;
                }

}


Header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using std::cout;
using std::endl;
#include <cstring>
using std::strlen;

class MyString
{

public:

    void strcomp(char  *string1,char *string2) ;// Compares the strings being passed
    void Ptrstrcomp(char  *string1,char*string2);//Compares the strings being pointed to by the pointer being passed

    void strnncomp(char *string1,char *string2,int val);
    void Ptrstrncomp(char*string1,char*string2,int val);

    void strcatt(char *string1,char *string2);
    void Ptrstrcat(char *string1,char *string2);

    void strncatt(char *string1, char *string2, int d);
    void Ptrstrncat(char * string1, char * string2, int v);

    void result(int x);


};

#endif // MYSTRING_H


Driver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using std::cout;
using std::endl;

#include "mystring.h"

int main()
{

   char string1[]="Grey  test";
   char string2[]="Great Potato";
   char *Ptr1=&string1[0];
   char *Ptr2=&string2[0];


    cout<<"Welcome"<<endl;

    MyString object;

    object.strcomp(string1,string2);
    object.Ptrstrcomp(Ptr1,Ptr2);

    object.strnncomp(string1,string2,5);
    object.Ptrstrncomp(Ptr1,Ptr2,7);

    object.strcatt(string1,string2);
    object.Ptrstrcat(Ptr1,Ptr2);

    object.strncatt(string1,string2,8);
    object.Ptrstrncat(Ptr1,Ptr2,6);

return 0;


}
Pages: 12