pointers

why cant i use .length(); command to find the length of this pointer?
and i also get garbage values when printing the location aswell
1
2
3
4
5
6
7
8
9
10
11
12
  string s1 = "Matt";
	int n1 = 13;
	int n2 = 7;

	string* pS1=&s1;
	int* pN1=&n1;
	int* pN2=&n2;
	cout << &pS1 << endl;
	system("pause");
	system("cls");
	return 0;
}
Last edited on
Where are you using length?

Are you saying pS1->length() doesn't work?

Doing "cls" immediately after your cout is a sure way of making it hard for you to see what's going on.
"Are you saying pS1->length() doesn't work?" yes it didnt
i changed that im sorry i didnt see that the "cls" and why do i get garbage values when i print them?
Last edited on
For the sake of a few extra lines of code we can all copy/paste for ourselves, what you're saying doesn't make sense.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ cat proj.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string s1 = "Matt";
  int n1 = 13;
  int n2 = 7;

  string *pS1 = &s1;
  int *pN1 = &n1;
  int *pN2 = &n2;
  cout << *pS1 << endl;
  cout << pS1->length() << endl;
  return 0;
}
$ g++ proj.cpp
$ ./a.out 
Matt
4

Works for me.
i really dont know but i have gotten trash values for some reason when i execute but when i used this it works and i taught the length would come as "3" because matt counts as 0 1 2 3?
Last edited on
The length of "Matt" is 4.
0, 1, 2, 3 comprises 4 indices; array indices start at 0. There are still 4 characters in "Matt".
Last edited on
It's because a string could be empty, which would have a length of 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 string s1 = "Matt";
	int n1 = 13;
	int n2 = 7;

	string* pS1=&s1;
	int* pN1=&n1;
	int* pN2=&n2;
	cout << &pS1 << endl; //this is the address of the pointer.  
//that is, you now have string** type and are printing that second layer of 
//abstraction which is a nonsense value when printed.   *pS1 gets you back to s1 from the pointer: eg 
//cout << *pS1;
//or cout << *pS1.length();  which is the same as {pS1->lenght() or 
//pS1[0].length()} depending on what syntax you like best. 
	system("pause");
	system("cls");
	return 0;
}
Last edited on
Topic archived. No new replies allowed.