Could someone explain this program?

The following is a homework assignment. There are certain functions in this program that I don't fully understand, as I had to get partial help at a tutoring center.
The following functions with *** are where my confusions are coming from.


/* *** The instructions for this function were: Create a method called “copy” that takes 2
char array parameters. This method should copy the data in the second parameter into the
first parameter. You should use a loop in this method.
I don't fully understand the second line in this function.? */

void copy(char *array1, char array2[]) {
for (int i = 0; i < sizeof(array1) / sizeof(*array1); i++) {
array1[i] = array2[i];
}
}

//This one is fine
int compare(char array1[], char array2[]) {
if (array1 < array2)
return -1;
else if (array1 == array2)
return 0;
else
return 1;
}

/* *** The instructions for this function were: Create a method called “concat” that takes three char array parameters. This method should concatenate the second string on to the end of the first string and store the result in the third string. My tutor kept telling me to use these statements: (for (int i = 0; i < (sizeof(array1) / sizeof(*array1)) / 2; i++)) meanwhile I have no idea why he tells me to do it this way. */


void concat(char array1[], char array2[], char array3[]) {
for (int i = 0; i < (sizeof(array1) / sizeof(*array1)) / 2; i++) {
array3[i] = array1[i];
}
for (int i = (sizeof(array1) / sizeof(*array1)) / 2; i < sizeof(array1) / sizeof(*array1); i++) {
array3[i] = array2[i];
}
}

//this is obviously good
int main()
{
char array1[4] = { 'a', 'b', 'c', '\0'};
char array2[4] = { 'a', 'b', 'd', '\0'};
char array3[8];

copy(array1, array2);
cout << compare(array1, array2) << endl;
print(array1);
system("pause");
return 0;
}

Last edited on
1
2
3
4
5
void copy(char *array1, char array2[]) {
	for (int i = 0; i < sizeof(array1) / sizeof(*array1); i++) { 
		array1[i] = array2[i];
	}
}


in this function
sizeof(array1) / sizeof(*array1)
always will return a constant number, most likely 1. Because you can not return the size of array this way, this statement just only returns the size of the data type.
All these functions are written wrong. Lines you have problems with do not do what expected and whole fuctions are incorrect because of that.

why does this function need pointer variables?
Because it is impossible to write it without them. How would you do so?

I'm good with why it needs pointers, but the assignment doesn't call for pointers, and i'm not sure how I would do it without pointers now. I'll have to have a relook at the whole assignment :/
Have you take a look in the memcpy implementation ?
Topic archived. No new replies allowed.