array of pointers confusion

The purpose of the code is to practise on an array of pointers.

I want to see this output: touch the surface

I would like to receive some corrections to make it work. Currently, it outputs:
touc the surfac surface.

I am confused...i would appreciate some help.

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>
#include <stdlib.h>

using namespace std;

int main()
{
    char *s[]={"touch",
               "the",
               "surface",
              };
    char **ptr;

    ptr=s;
    int i,j;
    for(j=0; s[j]!=s[3]; j++)
    {
        for(i=0; s[i]!='\0'; i++)
            cout <<  *(*(ptr+j)+i);
        cout << " "; 
    }
    return 0;
}


some tips:
*(ptr+j) --> i choose elements of the array (aka one of the 3 available strings)
*(*(ptr+j)+i)--> i choose letters one after the other from each string.
Last edited on
i'm terrible at C, but remember an array of size 3 means you should only ask for elements 0,1, and 2. I see on line 16 you're using s[3] in your for condition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//#include <iostream> // C++
#include<stdio.h>

int main()
{
	char *s[]= {"touch","the","surface"};
    
	for(int j=0; j<3; j++){
		for(int i=0; s[j][i]!='\0'; i++){
			//std::cout <<  s[j][i];  // C++
			printf("%c",s[j][i]);
		}
		//std::cout << " ";  // C++
		printf(" ");      
	}
	
return 0;
}
Thank you. My 'version' using pointers.

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

#include <iostream>
#include <stdlib.h>

using namespace std;



int main()
{
    char *s[]={"touch",
               "the",
               "surface",
              };
    char **ptr;

    ptr=s;
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0; *(*(s+i)+j)!='\0'; j++)
            cout << *(*(s+i)+j);
        cout << " ";
    }
    cout << "\n";
    return 0;
}
Line 18 should be
for(i=0; s[j][i]!='\0'; i++)
Can you spot the difference?

You were comparing an array of char (i.e. s[i]) to a char (i.e '\0')

Since you're only experimenting for the sake of knowledge, I won't try to correct the rest of your code, except to make a point about the comparison in line 16; consider the following code:
1
2
3
4
int  nums[4] = {24, 25, 26, 27);
...
for (int i = 0; nums[i] != nums[4]; ++i)
...


The problem here, is that there is no nums[4], and if by chance you access some random data outside the bounds of the array without crashing the program, there's every possibility that this loop goes on indefinitely. Also, if the nums array members have been changed since initialisation, then it's possible that nums[x] == nums[y] - granted, that isn't likely to happen with pointers, but you do see the point, it's a bad comparison.
Sorry, I can't help myself:

You're using <iostream> and namespace std, you should you use <cstdlib>, not <stdlib.h>
Topic archived. No new replies allowed.