Could someone explain these lines of code?

Okay, I have a homework assignment that tutor partially helped me with on certain functions, and I don't fully understand it, but I want to. I find the best way for me to learn is not to have programs written for me, but to have already written code be explained for me, so I want to divide this into parts.

Could you please just //comment at the end of each line that contains a ***, explaining what the line means/does?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print(char a[]) {
int i = 0;
***while (a[i] != char('\0')) {
***cout << a[i] << std::endl;
i++;
}
}



***void copy(char *array1, char array2[]) { //why does this function need a pointer for *array?
***for (int i = 0; i < sizeof(array1) / sizeof(*array1); i++) {
***array1[i] = array2[i];
}
}
Last edited on
closed account (28poGNh0)
When declaring an array ( (e.i char array[] = "car") The forth element(array[3] will contains a null term character ( '\0')

1
2
3
4
5
6
7
8
void print(char a[]) 
{
int i = 0;
***while (a[i] != char('\0')) {// if the a[i] is a null term char end loop .
***cout << a[i] << std::endl;// print character . a[0] the first,a[1] the second ...
i++;
}
}


By using pointers we can avoid elements transfert and just pointing at them
(e.i array2 gets all the elements array1 points to an array)

1
2
3
4
***void copy(char *array1, char array2[]) { //above
***for (int i = 0; i < sizeof(array1) / sizeof(*array1); i++) {
// This line sizeof(array1) / sizeof(*array1) guess! the size of the array1
***array1[i] = array2[i];//copy the element array[i] to array1[i]  
Last edited on
what about the next part?
Last edited on
closed account (28poGNh0)
Do you remember this line ? using namespace std;
well std namespace contains a lot of functions ,macros ,variables ....
so It's more efficient to use only what you need .

Look at this example :
1
2
3
4
5
6
7
8
9
# include <iostream>
using namespace std;

int main()
{
    cout << "Hello world" << endl;
    
    return 0;
}


The compiler know that cout and endl belong to std namespace;

Now ,after removing using namespace std

1
2
3
4
5
6
7
8
# include <iostream>

int main()
{
    std::cout << "Hello world" << endl;

    return 0;
}


You'll got an error ,if you try to compile it .
So to fixe that just add std:: before endl because the compiler doesn't know about endl;

Thats a half responds if you got it I'll add the next half but I need 1 000 000$
Topic archived. No new replies allowed.