Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer to an array in a function

Status
Not open for further replies.

powerb23

Technical User
Sep 11, 2003
11
0
0
US
Hi,
I wanted to find out how i would point to the array arr in function get(char *p) so that i ould print the contents of this array.
Your help will be appreciated.



int main(){
char * ptr = NULL:

get(ptr);
printf("contents: %s:, ptr);
}

void get(char *p){
char [5]mm = NULL;
int i;

for(ii = o;i <5;i++){
mm = i;
}

p = mm; /*I'm not sure about this part */
}

 
iam afraid i didnt get ur question/code rite.. 'but i have a hunch that u need sumthing like dis
Code:
main()
{
  int a[]={1,2,3,4};

   get(a);
}
void get (int *p)
{
 int i = 0;
 for (i=0; i < 3; ++i)
   printf(&quot;%d\n&quot;, p[i]);

this is jus d basic stuff. u may also pass the array max subscript in the function so that u know when the loop must terminate.
here my function get already &quot;knows&quot; that index
the same thing can be done for a character array..
here there is 1 advantage
the loop conditon can be replaced by
Code:
for (i = 0 ; p[i]!='\0' ; ++i)
or
for (i = 0 ; p[i] ; ++i)
hope this helps
 
I thought you wanted to pass a charcter pointer to a sub-function, assign values to it & print it back in the main function. Please find below a sample function which achieves the same.

Code:
#include <stdio.h>
#include <malloc.h>

void get(char **p)
{ 
	unsigned int i; 
	char *q;
	q=*p;
	
	for(i=0;i<5;i++)
	{ 
		*q = 'a';
		q++;
	} 
	*q = '\0';
}

int main()
{ 
	char *ptr;
	unsigned int i=0;

	ptr = (char*)malloc(sizeof(char) * 6);

	if(ptr != NULL)
	{
		get(&ptr); 
		printf(&quot;contents: %s\n&quot;, ptr); 
		free(ptr);
	}
	return 1;
} 
[\code]
 
Thanks alot for the help. i used the for loop and got the program up and running.
All your help has been greatly appreciated
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top