about pointer & arrays

Im trying a program that asks the user to enter his 1st name
to store it in an array of char that has 20 size.
then declaring another array of the same type and size
to copy the 1st string to the second array
using function.

so this is my code.

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
#include <iostream>
using namespace std;
char copystr( char *s1, char *s2);
int main (void)
{
int size=20;
char array[size];

char *ptr1;
char *ptr2;
ptr1=&array[0];
ptr2=&array2[0];
for (int i=0;i<size;i++){
cin>>*ptr1;
}
char array2[size];
copystr(&ptr1,&ptr2);
cout << "Second array is "<<array2[size];
}
char copystr( char *s1, char *s2)
{
	
	*s1=*s2;
	return *s2;
}



but there is something wrong :(



Thanks for helping .
but there is something wrong :(

Then the answer is simple: change it so that there is no longer something wrong.

(Answering with the same level of specificity with which the question was asked.)
There is already a function which does this. So no need to re-create one. Its in the cstring header.
The function is:
strcpy(destination, source)

Here is an example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring> //We need this for strcpy

using namespace std;

int main()
{
    const int SIZE = 20;

    char name[SIZE]; //This will hold the name
    char name_copy[SIZE]; //We will copy the name to this

    cout << "Enter your first name: ";
    cin >> name;

    cout << "\nName is " << name << " eh?" << endl;

    strcpy(name_copy,name); //Copies name to name_copy

    cout << "name_copy is now " << name_copy << " too!" << endl;

    return 0;
}
Last edited on
1
2
3
4
5
6
7
char * foo;
*foo // dereference a pointer
// is equivalent to
foo[0] // dereference a pointer
// and the type of the result is obviously
char
// one character.  Not a string. Not an array. Not a pointer. 

There is no assignment operator that would copy contents of one array into an another array.

There is std::copy and there are multiple C-string-aware copy functions. However, if your task is to write copystr() on your own, then you must use the basic constructs for educational purposes.

You do have a logical problem on the input as well; Every person in the world has 20 characters in their forename. Or do they? Your program thinks so.


How long is a piece of string? C-strings have a convention about that.
Topic archived. No new replies allowed.