School assignment

Hi all,

Could you please help me with a school assingment? we need te rewrite all chars to pointers, and i cant figure it out.

Here is the start program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int main ()
{
   char zin1[] = "Wat is je naam? ";
   char zin2[] = "\nHallo, ";
   char zin3[] = ", welkom in Venlo!\n\n";
   char zin4[80];
   int i, n, lengte;

   cout << zin1;
   cin >> zin4;
   
   for (n=0; zin4[n] != '\0'; n++);
   
   lengte = n;
   zin4[n++] = '.'; zin4[n++] = '\n'; 
   for (i=0; i < lengte; n++, i++)
   {
       zin4[n] = zin4[i];
   }
   zin4[n] = '\0';
   cout << zin2 << zin4 << zin3;
   
   cout << endl;
   system("PAUSE");
   return 0;
}


And we need to use
1
2
3
4
   char * p1 = "Wat is je naam? ";
   char * p2 = "\nHallo, ";
   char * p3 = ", welkom in Venlo!\n\n";
   char * p4;


There is no difference between char * p1 = "Wat is je naam? "; and char zin1[] = "Wat is je naam? "; except that you can't modify the first one (in fact it is not correct. It should be const char*, but compilers for some reason allow it).

for p4 you'll have to allocate some memory (with new and don't forget to delete it)
Last edited on
A pointer (char * p1) can basically be seen as a variable pointing to the start of an array. So, p1 points to the array at some address in memory where the array "Wat is je naam? " is stored". That said, you can just replace zin1, zin2 and zin3 with p1, p2, and p3.

You cannot do the same with p4 directly. The difference is that the compiler does not know the length of the data at p4. As you can see in your code however, the length of zin4 is given (80). Now, if you let p4 point to zin4 it will work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main ()
{
   char * p1 = "Wat is je naam? ";
   char * p2 = "\nHallo, ";
   char * p3 = ", welkom in Venlo!\n\n";
   char * p4;
   char zin4[80];
   p4 = zin4;
   int i, n, lengte;

   cout << p1;
   cin >> p4;
   
   for (n=0; p4[n] != '\0'; n++);
   
   lengte = n;
   p4[n++] = '.'; p4[n++] = '\n'; 
   for (i=0; i < lengte; n++, i++)
   {
       p4[n] = p4[i];
   }
   p4[n] = '\0';
   cout << p2 << p4 << p3;
   
   cout << endl;
   system("PAUSE");
   return 0;
}


Nu heb ik zo'n lekkere vlaai uit Venlo verdiend ;) (In English: Now I deserved some of that pie from Venlo).
Last edited on
Topic archived. No new replies allowed.