Posted by Sharvil Nanavati on 2001-04-06
> #define DictionarySize 200
> #define DictionaryStart 0
>
> char* FindCode(char* ENTRY);
>
> char* FindCode(char* ENTRY)
> {
> for(int z = DictionaryStart; z < DictionarySize; z++)
> {
> if( !strcmp(Dictionary[z], ENTRY ))
> {
> return Dictionary[z];
> }
> }
> }
>
>
> sorry about last post... cut and paste happy..... :)
>
> this takes in the pointer to the array... and returns a pointer to an
> array
> the * next to the char stands for pointer. so char means 'a' or '4'
> and
> char* is "hello/0" or "this is a string/0"
>
> a function cannot change the string ENTRY... to change the ENTRY you
> would
> use it like this
>
> void FindCode(char& ENTRY);
>
> the & passes the ORIGINAL pointer... while * causes the OS to make a
> copy of
> the string and pass it.
>
> this also works with classes(C++) or structures....
Actually, let me make a couple of corrections: the ampersand (&) only
works in C++ (it's called passing a value by reference), and you _can_
actually modify the string ENTRY the way it was shown before. What you
cannot do is change the memory address ENTRY points to. What is
happening is this:
Allocate memory for array by declaring.
char ENTRY[100];
therefore, ENTRY points to the first letter of the string. ENTRY + 1
points to the _second_ letter of the string. Why? Because a string
allocates _consecutive_ bytes of memory for itself. Therefore, if ENTRY
points to memory location 73243 (or whatever) then the VALUE of the
byte AT that location is the first letter in the string. Hence, when we
say ENTRY + 1, we are referring to the memory address 73244 (which
would hold the second letter of the string).
When you pass a string to a function, you are passing the address of
the string.
void main()
{
char ENTRY[100] = "Hello World";
printf("%i\n", ENTRY);
Display(ENTRY);
}
void Display(char *ENTRY_PTR)
{
printf("%i\n", ENTRY_PTR);
}
When this program runs, it will display the memory location ENTRY
points to. It _is_ true that the value passed to the function is
copied, but the MEMORY ADDRESS is copied, not the actual VALUE. Hence,
both ENTRY_PTR and ENTRY both point to the same string. By passing it
this way, you cannot change what ENTRY points to, but you can change
the string itself.
void main()
{
char ENTRY[100] = "Hello World";
printf("%s\n", ENTRY);
Change(ENTRY);
printf("%s\n", ENTRY);
}
void Change(char *ENTRY_PTR)
{
strcpy(ENTRY_PTR, "Goodbye World!");
}
This program will produce the output:
Hello World
Goodbye World!
As you can see, the string CAN be modified. I hope this clears up the
issue. :) If there are any errors, please make corrections where
necessary.
Cheers,
Sharvil Nanavati
__________________________________________________
Do You Yahoo!?
Get email at your own domain with Yahoo! Mail.
http://personal.mail.yahoo.com/
Previous post | Next post | Timeline | Home