beginner question. using a pointer as a argument.  
Author Message
Reuomi





PostPosted: Visual C++ General, beginner question. using a pointer as a argument. Top

The code below was from a intro into functions and passign arguments. My question is why in the function "stringLength" you need to use a pointer rather than just a regular character variable


when i try without the pointer i get this error:
error c2109: subscript require array or pointer (vc++ just crashed so thats close to the right error)

int stringLength(char *str);

void main()
{
int strlength = stringLength("dan");
cout << strlength << endl;
}

int stringLength(char *str)// this is what to look at
{
int length = 0;
while (str[length] != '\0')
length++;

return length;
}



Visual C++1  
 
 
Bite Qiu - MSFT





PostPosted: Visual C++ General, beginner question. using a pointer as a argument. Top

I think the answer is pretty straightforward, as what compiler said, subscript require array or pointer. when you use str[length] that means you use subscript, that is only used for array or pointer.(Or write you own operator[], sorry i  know it must be a better way to explain this)

i suggest you to grab a book about C/C++ programming, read it through, and it should be much help. It is also lots of C/C++ programming tutorial available on the internet, try to find them use Google or Ask or whatever search engine. here i found some:

C++ Language Tutorial

C programming.com - Your Resource for C and C++ Programming

good luck

Bite



 
 
Simple Samples





PostPosted: Visual C++ General, beginner question. using a pointer as a argument. Top

If someone has a bag of rocks and takes out one rock and asks you how many rocks are in the bag, you can't answer the question because you can't see inside the bag nor can you take any rocks from the bag to count them.


It is much the same way when you give a function such as stringLength() a single character (rock) from a string (bag of rocks).