Passing/Returning arrays to/from functions (N00b question)

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

User avatar
Maevik
Chaos Rift Junior
Chaos Rift Junior
Posts: 230
Joined: Mon Mar 02, 2009 3:22 pm
Current Project: www.keedepictions.com/Pewpew/
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: Long Beach, CA

Passing/Returning arrays to/from functions (N00b question)

Post by Maevik »

Firstly, if this is the wrong place for this sort of question, I appologize in advance. I was under the impression this was a place for help with random shit.

Secondly, I've been doing too much coding lately I guess, since I just typed this whole fuckin post, then instead of hitting submit, I hit ctrl+F5... "Page Has Expired" Back button no help => Epic Fail

Ok, now to my issue:

Just for practice and such, I'm building a basic program that takes an array of characters and reverses the letters in it. I broke this algorithm into two parts:
1) Build a function that uses a for loop to reverse the order of the characters within the array.
2) Build a function that essentially left justifies the letters.

I tested both functions by copying the code into the main function and they work fine. My problem comes when using that as actual funcitons. I can pass the array into the function easily enough, but returning an array is giving me a whole mess of issues. My best guess is that using "return aname[20];" is returning the contents of the 20th slot of the array (which would be garbage data in the memory) but this still begs the question "How to I pass the entire array?"

PS I tried this by passing pointers instead of arrays and got the same problems -_-

Code: Select all

#include <iostream>

using namespace std;

char backward(char aname[20]);
char ljustify(char aname[20]);

int main()
{
	char name[20] = {'C','H','R','I','S'};
	char name2[20] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','S','I','R','H','C'};
	char test[20];


	cout << name << endl;
                cout << backward(name);
	cout << ljustify(name2);
	cout << endl;
	cout << name;

                test = backward(name);
}

char backward(char aname[20])
{
	char bname[20];

	for(int i = 0 ; i < 20 ; i++)
	{
		bname[i] = ' ';
	}

	for(int i = 0 ; i < 20 ; i++)
	{
		bname[i] = aname[(19-i)];
		
		for (int j = 0 ; j < 20 ; j++)
		{
			cout << bname[j];
		}
		cout << endl;
	}

	return bname[20];
}

char ljustify(char aname[20])
{

	while ( aname[0] == ' ' )
	{
		for ( int i = 0 ; i < 20 ; i++ )
		{
			if ( aname[0] == ' ' )
			{
				for ( int j = 0 ; j < 19 ; j++ )
				{
					aname[j] = aname[j+1];
				}
				aname[19] = ' ';
			}			
		}
		for (int k = 0 ; k < 20 ; k++)
		{
			cout << aname[k];
		}
		cout << endl;
	}
	for (int k = 0 ; k < 20 ; k++)
	{
		cout << aname[k];
	}
	return aname[20];
}
My love is like a Haddoken, it's downright fierce!
User avatar
Maevik
Chaos Rift Junior
Chaos Rift Junior
Posts: 230
Joined: Mon Mar 02, 2009 3:22 pm
Current Project: www.keedepictions.com/Pewpew/
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: Long Beach, CA

Re: Passing/Returning arrays to/from functions (N00b question)

Post by Maevik »

EDIT: Sorry, about the pointers. Trying this with pointers gives me an error for the value being passed, not returned...

Exact error:
Error 1 error C2664: 'ljustify' : cannot convert parameter 1 from 'char (*)[20]' to 'char *[]'

Exact Code:

Code: Select all

#include <iostream>

using namespace std;

void ljustify(char * aname[20]);

int main()
{
	char name[20] = {'C','H','R','I','S'};
	char name2[20] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','S','I','R','H','C'};
	char test[20];


	cout << name << endl;
	cout << ljustify(&name2);
	cout << endl;

	
	cout << name;



}

void ljustify(char * aname[20])
{

	while ( *aname[0] == ' ' )
	{
		for ( int i = 0 ; i < 20 ; i++ )
		{
			if ( *aname[0] == ' ' )
			{
				for ( int j = 0 ; j < 19 ; j++ )
				{
					*aname[j] = *aname[j+1];
				}
				*aname[19] = ' ';
			}			
		}
		for (int k = 0 ; k < 20 ; k++)
		{
			cout << *aname[k];
		}
		cout << endl;
	}
	for (int k = 0 ; k < 20 ; k++)
	{
		cout << *aname[k];
	}
	//return aname[20];
}
My love is like a Haddoken, it's downright fierce!
Scoody
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 65
Joined: Fri Feb 06, 2009 2:07 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by Scoody »

Arrays are kind of special, they're really pointers, so when you pass yourFunc(char array[]), and set a value inside that function, you're just editing the actual array.

//Edit: for the textjustify, just use the stream manipulators, in code example

Code: Select all


#include <iostream>
#include <iomanip>
using namespace std;
void arrfunc(int arr[],int length);

int main() 
{
  int hello[4]; // new array with no values
  arrfunc(hello,4); // use the function to set values to the array
  for(int i = 0; i < 4; i++)
    cout << hello[i] << endl;

  cout << right << setw(40) << "Right justified text" << endl;
}


void arrfunc(int arr[],int length) 
{
  for(int i = 0; i < length; i++)
    arr[i] = i+1; // this is setting the values of the hello array in main
}

User avatar
Maevik
Chaos Rift Junior
Chaos Rift Junior
Posts: 230
Joined: Mon Mar 02, 2009 3:22 pm
Current Project: www.keedepictions.com/Pewpew/
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: Long Beach, CA

Re: Passing/Returning arrays to/from functions (N00b question)

Post by Maevik »

Ok, I remember reading on arrays being pointers now that you bring it up. Does this mean that arrays essentially cannot be passed between functions? At least not without adding them to the heap?
My love is like a Haddoken, it's downright fierce!
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

its not the best solution, but thought its one you might understand.
hope it helps. ps: i was not sure what you meant buy left justify, so i kinda just did it like the proper meaning of left justify is.

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *reverseString(char *data);
char *leftJustify(char *data);

char *reverseString(char *data)
{
    char *temp = (char*)malloc(sizeof(char)*strlen(data));
    for(int a = 0;a < strlen(data);a++)
    {
        temp[a] = data[strlen(data)-a-1];
    }
    temp[strlen(data)] = '\0';
    return temp;
}

char *leftJustify(char *data)
{
    int a = 0;
    if(data[a] == ' ')
    {
        while(data[a] == ' ')
        {
            a++;
        }
    }
    char *temp = (char*)malloc(sizeof(char)*strlen(data)-a);
    for(int b = 0;b < strlen(data)-a;b++)
    {
        temp[b] = data[b+a];
    }
    return temp;
}

int main (void)
{
    printf("%s\n", reverseString("asdf"));
    printf("%s\n", leftJustify("      asdf"));
    return 0;
}

Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

also this notion that you have to pass the size of the array is just stupid.

sizeof(array) give us how many bytes the array holds
sizeof(data type) give us how many bytes the data type holds.

so, sizeof(array)/sizeof(data type) = number of elements in array.

Code: Select all

void printArray(char data[])
{
    for(int a = 0;a < sizeof(data)/sizeof(char);a++)
    {
        printf("%c\n",data[a]);
    }
}

// note that sizeof(data) will work on its own in this situation and any situation where the
// data type is char, becayse char is only 1 byte and X/1 will always = X.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
wtetzner
Chaos Rift Regular
Chaos Rift Regular
Posts: 159
Joined: Wed Feb 18, 2009 6:43 pm
Current Project: waterbear, GBA game + editor
Favorite Gaming Platforms: Game Boy Advance
Programming Language of Choice: OCaml
Location: TX
Contact:

Re: Passing/Returning arrays to/from functions (N00b question)

Post by wtetzner »

avansc wrote:

Code: Select all

void printArray(char data[])
{
    for(int a = 0;a < sizeof(data)/sizeof(char);a++)
    {
        printf("%c\n",data[a]);
    }
}
Actually "sizeof(data)" will give the size of the pointer to the array, not the length of the array. It will only give the array length if it's a static array that was declared in the same scope.
The novice realizes that the difference between code and data is trivial. The expert realizes that all code is data. And the true master realizes that all data is code.
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

wtetzner wrote:
avansc wrote:

Code: Select all

void printArray(char data[])
{
    for(int a = 0;a < sizeof(data)/sizeof(char);a++)
    {
        printf("%c\n",data[a]);
    }
}
Actually "sizeof(data)" will give the size of the pointer to the array, not the length of the array. It will only give the array length if it's a static array that was declared in the same scope.
why dont you try and find a situation where that function does not work.... i would be interested really...
and ps: by definition arrays are always static.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Scoody
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 65
Joined: Fri Feb 06, 2009 2:07 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by Scoody »

// Edit: Oh, so much happened while I was writing ...
sizeof(array) will only give you 4 bytes, since that's the size of a pointer, unless it's statically created and you're in the same block it was created in.

Code: Select all

#include <iostream>

using namespace std;
void func(char test[]);

int main() 
{
    char world[6];
    cout << sizeof(world) << endl; // 6
    char *hello = new char[6];
    cout << sizeof(hello) << endl; // 4 (sizeof int, pointer)

    func(world); // outputs 4 (sizeof int, pointer)
    func(hello); // outputs 4 (sizeof int, pointer)
}


void func(char test[])
{
  cout << sizeof(test) << endl;
}
User avatar
wtetzner
Chaos Rift Regular
Chaos Rift Regular
Posts: 159
Joined: Wed Feb 18, 2009 6:43 pm
Current Project: waterbear, GBA game + editor
Favorite Gaming Platforms: Game Boy Advance
Programming Language of Choice: OCaml
Location: TX
Contact:

Re: Passing/Returning arrays to/from functions (N00b question)

Post by wtetzner »

avansc wrote:why dont you try and find a situation where that function does not work.... i would be interested really...
OK

Code: Select all

#include <iostream>
using namespace std;

void printArray(char data[])
{
    for(int a = 0;a < sizeof(data)/sizeof(char);a++)
    {
        printf("%c\n",data[a]);
    }
}

int main(int argc, char *argv[])
{
    char items[26];
    for(int i = 0; i < 26; i++)
        items[i] = (char)('a' + i);

    printArray(items);

    return 0;
}
It will print a-d if you're on a 32 bit processor, or a-h if your on a 64 bit processor, since a pointer on a 32 bit proc is 4 bytes, and a pointer on a 64 bit proc is 8 bytes.
and ps: by definition arrays are always static.
I meant an array that's statically allocated.
The novice realizes that the difference between code and data is trivial. The expert realizes that all code is data. And the true master realizes that all data is code.
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

mmm. i may have made a boo boo. let me just do some research quick.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

okay, yeah i see what you guys are saying. and i appologize for my mistake. i primaray use char* not [] of anykind.

that being said. you can still do it without passing the size.

Code: Select all

void test(char test[])
{
    int a = 0;
    while(test[a+1] != NULL)
    {
        printf("%c",test[a]);
        a++;
    }
    printf("%c\n",test[a]);
}
that worked for me, i dont know what would happen on a 64 bit proc. but i think it would be fine.
anyways. i would appreciate if someone tried it out to see if it worked.

thanks.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
wtetzner
Chaos Rift Regular
Chaos Rift Regular
Posts: 159
Joined: Wed Feb 18, 2009 6:43 pm
Current Project: waterbear, GBA game + editor
Favorite Gaming Platforms: Game Boy Advance
Programming Language of Choice: OCaml
Location: TX
Contact:

Re: Passing/Returning arrays to/from functions (N00b question)

Post by wtetzner »

avansc wrote:okay, yeah i see what you guys are saying. and i appologize for my mistake. i primaray use char* not [] of anykind.

that being said. you can still do it without passing the size.

Code: Select all

void test(char test[])
{
    int a = 0;
    while(test[a+1] != NULL)
    {
        printf("%c",test[a]);
        a++;
    }
    printf("%c\n",test[a]);
}
that worked for me, i dont know what would happen on a 64 bit proc. but i think it would be fine.
anyways. i would appreciate if someone tried it out to see if it worked.

thanks.
It works, although I don't know if you can count on the bytes following the array in memory to be zero all the time. Also, you couldn't use the same approach with an array of integers, since the array couldn't contain any zeros then.

As a c string, it still wouldn't work, as they are zero terminated. You could compare against 0 instead of NULL, but currently if your array has 4 0's in a row, it will stop there.
The novice realizes that the difference between code and data is trivial. The expert realizes that all code is data. And the true master realizes that all data is code.
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Passing/Returning arrays to/from functions (N00b question)

Post by avansc »

ummm.. well i tried with 5 zeroes and it still worked fine. tried 4 also.
i didnt try char* data = "100000";
i did a pure array.

edit: i just tried that function with char *dat3 = "12340000001234";
and it worked fine.
i also tried it with char dat[] = {'1','2','3','4','0','0','0','0','0','0','1','2','3','4'};
and it worked fine.

null is '\0' not 0
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
wtetzner
Chaos Rift Regular
Chaos Rift Regular
Posts: 159
Joined: Wed Feb 18, 2009 6:43 pm
Current Project: waterbear, GBA game + editor
Favorite Gaming Platforms: Game Boy Advance
Programming Language of Choice: OCaml
Location: TX
Contact:

Re: Passing/Returning arrays to/from functions (N00b question)

Post by wtetzner »

I was wrong. You only need one zero after the first item. And I didn't mean the character '0', I meant a character with ascii value 0.

Code: Select all

void test(char test[])
{
    int a = 0;
    while(test[a+1] != NULL)
    {
        printf("%c",test[a]);
        a++;
    }
    printf("%c\n",test[a]);
    printf("a = %u\n",a);
}

int main(int argc, char *argv[])
{
    //char items[26];
    char items[26];
    for(int i = 0; i < 26; i++)
        items[i] = (char)('a' + i);
    items[1] = 0;
    test(items);

    return 0;
}
This never gets past the first item.

So if you're looping through a char array that's intended to be a series of bytes, rather than characters, you can't have any 0's in it.
The novice realizes that the difference between code and data is trivial. The expert realizes that all code is data. And the true master realizes that all data is code.
Post Reply