strcopy problems

hi.
I am writing a program to copy a string without using the strcopy funcion.
I am copying from a to b, but I am not able to delete from b to be ready for another input.
I have tried numerous ways, both with for loop and delete []b but nothing seems to 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
32
33
34
35
36
37
38
  #include <iostream>
using namespace std;

char strcpy2 (char* b, char* a);

int main()
{
    char a[1000], b[1000];
    while (cin.getline(a, 1000))
    {
        cout << "strcpy2(b, \"" << a << "\");" << endl;
        strcpy2(b, a);
        cout << "b = \"" << b << "\";" << endl;
    }

    return 0;
}

char strcpy2 (char* b, char* a)
{


    for (int i = 0 ; i < *a ; i++)
    {
        b[i] = a[i];
    }
    delete b;
    b = NULL;





return 0;


}
A copy operation that kills the source object would not be a copy.

> but I am not able to delete from b to be ready for another input.
You do not need to do anything prior to a reading.
If you do want for b to be considered "empty" then you could simply b[0] = '\0';

Only delete what you new
Only delete[] what you new[]

Also, it is obvious that line 28 has no effect, as it is modifying a pointer local to the function.
1
2
3
4
5
6
7
8

const int SIZE = 1000;

void strcpy2(char a[], char b[], const int SIZE){

	for (int i = 0; i < SIZE; i++)
		b[i] = a[i];
}


Arrays are default pass by reference because array names are just pointers anyway no need to get fancy. Just pass and copy if you want.
Last edited on
Thanks, used mobutus solution and it worked.

If however i would have used it like I started to how would would that be presented and how to get the null-terminated copied over as well. It seems that was my problem.
This maybe what you are thinking about.

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;

const int SIZE = 3;

char *strcpy2(const char * a, const int SIZE){

	char *b = new char[SIZE];
	for (int i = 0; i < SIZE; i++)
		b[i] = a[i];
	return b;

}

int main(){

	char a[] = { 'A', 'B', 'C' };
	char *ptr = strcpy2(a, SIZE);
	for (int i = 0; i < SIZE; i++)
		cout << ptr[i];
	delete[] ptr;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.