*char to char[256]

I have this function over here.

1
2
3
4
char *fun(){
	char a[256]="abcdefg";
	return &a[0];   //???
}


witch is supposed to return whole array
like this

1
2
char b[256];
b = fun();


but it doesn't work

SOS



Last edited on
char* is not an array, it's a pointer. It's best not to think of 'char*' as a string, but instead, think of it as a pointer to a string.

C-style strings are not single objects, but are a series of variables (one for each character), each one must be copied individually. There are functons which automate this process so it can be done in one step:

1
2
3
4
5
char a[256] = "abcdef";
char b[256];

// copy 'a' to 'b'
strcpy(b,a);


Typically you do not return pointers or arrays from functions for this kind of thing (for several reasons). Instead, you pass a pointer to a buffer you want to fill and have the function fill that pointer. For example to do what you are trying to do above, you could do this:

1
2
3
4
5
6
7
8
9
void fun(char* buf)
{
  strcpy(buf,"abcdefg");
}

// .. elsewhere ..

char b[256];
fun(b);


This works by giving 'fun' a pointer to your 'b' string, so that it can modify that string.
Last edited on
on the similar lines i have a question,

char *p = "abc";

cout << p; // this displays abc

p = "bye";

cout << p; // this displays bye

My understanding is that * will deference the pointer and will give a value and without * will give the address. But here p="bye" works and able to display it also ....can some one clear my doubt ?
To make things a little simpler, let's suppose you're not calling std::cout.operator<<(). Let's suppose you're calling a function printString().
1
2
3
4
5
6
void printString(const char *str){
	for (;*str;str++)
		printf(*str);
}
//and it's called like this:
printString(p);

This is what's happenning:
1. When you pass p, which is a pointer (pointers are memory addresses) to a character string, you're passing a copy of a memory address.
2. The function receives a memory address. It doesn't actually care what it points to; it will execute whether it points to a valid string or to something completely different.
3. Simplified the function's loop looks like this:
while (the char value at the memory address 'str' is not zero){
print the char value at the memory address 'str';
increment the value of 'str' by 1;
}

The result is that the C string the original address pointed to (or whatever there was at that memory location) is printed correctly.
Thanks a lot ...clears my doubt ...
Topic archived. No new replies allowed.