Question concerning *

Hello,everyone.
I am learning the concept of pointers recently.
The reference book said when we declare a variable, * means a pointer.In common statement,* is used to transfer the value pointed by the pointer, and I am told that when * is used along with char (char*),it means a string.
But when I come across a certain program,it is very confusing to me, can anybody tell me what is the meaning behind each * in the program?

This program change every alpabet to capital letters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstring>
#include <cctype>       
using namespace std;

char *toUpper(const char *);   

int main(void)
{cout << toUpper("happy Birthday");}

char *toUpper(const char* ptr)        
{unsigned len = strlen(ptr);
char *newStr = new char[len];       
for(unsigned i=0;i<len;i++)
*(newStr+i) = toupper(*(ptr+i));  
return newStr;}
char *toUpper(const char* ptr) means that this is a function taking a char* argument and returnig a char*.
Here and in char *newStr the * means that variables used are pointers to chars ( C-Style strings ).
In *(newStr+i) = toupper(*(ptr+i)); * means that you are not using the value of the pointers but the values pointed.

This page coul help you : http://www.cplusplus.com/doc/tutorial/pointers.html
Last edited on
Thank you very much.
But I found another problem. After using this little program,it outputs the capital letters, but just after that, it also transfer some strange things.
if i use "Happy Birthday", it will return "HAPPY BIRTHDAYGRh"
How can I eliminate those strang strings?
Thank you
Last edited on
what does you code look like now??
The problem could ba that you are loosing your string terminator ( '\0' ),
Try to add it at the end of your string newStr+len-1='\0';
Last edited on
Thank you Buzzy, your suggestion is exactly what I want.
Here is my refined program

1
2
3
4
5
6
7
char* toupper(const char* ptr)
{unsigned len = strlen(ptr)+1;
char* newstr = new char[len-1];
for(unsigned i=0;i<len-1;i++)
*(newstr+i) = toupper(*(ptr+i));
*(newstr+len-1) = '\0';
return newstr;}
Topic archived. No new replies allowed.