Advertisement

Can change an array with a function w/o pointers?

Started by April 13, 2002 05:34 AM
4 comments, last by rhino2876 22 years, 8 months ago
I posted this in another thread, sorry if you are offended by double posts, but I wanted to see others input besides the people involved in the earlier thread. I thought that local variables within functions could not change values in main unless you use pointers. Here is something interesting that I experimented with. A function could change an array without pointers.
  
#include <stdio.h>

int test(char i[]);

int main()
{	
     char c[5] = "    ";	        
     printf("\n\n%d\n\n", test(c));	        
     printf("\n\n%s\n\n", c);	        
     return 0;
}

int test(char i[])
{    i[0] = ''H''; 
     i[1] = ''i'';	        
     return 1; 
}
  
CONSOLE OUTPUT: 1 Hi Press any key to continue Notice that I actually changed the first 2 elements of c[] with the i[] array that is local to the function test. I thought that local variable do not change values in main unless if you use pointers. Strange.
Rhino2876
When you pass something like

char i[]

to a function, you actually pass the pointer of the first element to that function.

The Wild Wild West - Desperado!
The Wild Wild West - Desperado!
Advertisement
Cool, is that for all arrays, or just character arrays?
Rhino2876
It works for all kinds of arrays. "char i[]" is the same as "char *i" (but only if you leave the length-field empty, otherwise (e.g. "char i[5]" it''s not quite the same).
I responded to this in the other thread. Please go to that thread for details.
You passed in the address of your local variable, so the function was able to modify it. This was addressed in the other thread, so this one is superfluous.

Thread closed.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! | Asking Smart Questions | Internet Acronyms ]
Thanks to Kylotan for the idea!

This topic is closed to new replies.

Advertisement