creating own "charcopy" function using pointers [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create my own char copy (like strcopy) function. It needs to be custom, I cannot use the one inside the std lib (Strcopy). I cannot change my char arrays to strings. I cannot use built in functions to copy the chars. i must use pointers to manipulate the array
I am trying to work off what the real strcopy looks like, but i cant seem toget mine to work. I THINK I want to create a pointer that points to strcpy(char destination,char source) and then I manipulate destination through source but nothing is copying over correctly and I just print out garbage. Please help open to all suggestions
void StrCpy(char *destination, char *source);
int main()
{
card card1[10], card2[10];
card1[0].cvalue = 1000;
card2[0].cvalue = 90000;
card *card1p = &card1[0];
card *card2p = &card2[0];
//set up card file to be read in
ifstream fin;
string finName;
//get file name from user
cout << "Enter file name...(cardFile.txt)" << endl;;
getline(cin,finName);
//open the file
fin.open(finName.c_str());
//check if cardFile.txt opens correctly
if(!fin.good())
{
cout << "Error with card file" << endl;
return 0;
}
else
{
card *deckPointer = NULL;
//prime fin
//fin >> deck[i].suit;
//fin >> deck[i].rank;
//fin >> deck[i].cvalue;
while(fin.good())
{
for(card1p = &card1[0]; card1p < &card1[10];card1p++)
{
fin >> (*card1p).suit;
fin >> (*card1p).rank;
fin >> (*card1p).cvalue;
}
}
}
StrCpy((*card2p).suit, (*card1p).suit);
cout << (*card2).suit << endl;
}
void StrCpy(char *destination,char *source)
{
char *p = destination;
*p = *source;
}

Usually the function is defined the following way
char * StrCpy( char *destination, const char *source )
{
char *p = destination;
while ( *p++ = *source++ );
return destination;
}
Yet another realization
char * StrCpy( char *destination, const char *source )
{
char *p = destination;
do
{
*p++ = *source;
} while ( *source++ );
return destination;
}
And one more
char * StrCpy( char *destination, const char *source )
{
for ( char *p = destination; *p = *source; ++p, ++source );
return destination;
}
or
char * StrCpy( char *destination, const char *source )
{
char *p = destination;
while ( *p = *source ) ++p, ++source;
return destination;
}

void StrCpy(char *destination,char *source)
{
char *p = destination;
*p = *source;
}
is not correct. Basically you're doing
destination[0] = source[0], which is not a actual copy.
You should read up on pointers. And formatting. And std::string.

Related

Why does this programme output the wrong value of the string in main? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 28 days ago.
Improve this question
The following code outputs the correct string in the parameters function, but the incorrect string in main.
Obviously something is going wrong, but I can't see what it is. Thanks.
#include <iostream>
#include <string>
using namespace std;
typedef struct sim {
const char* dir;
} sim;
string convertToString(char* a)
{
string s(a);
return s;
}
int parameters(sim *sdata, char **argv, int argc){
char *filename;
string token;
string delimiter = "=";
size_t pos = 0;
string s;
for (int i = 0; i < argc; ++i){
s = convertToString(argv[i]);
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
s.erase(0, pos + delimiter.length());
}
if(token == "-dir"){
sdata->dir = s.c_str();
cout << sdata->dir << endl;
}
}
}
int main(int argc, char** argv) {
sim * sdata = (sim*)malloc(sizeof(sim));
parameters(sdata, argv, argc);
cout << sdata->dir << endl;
free(sdata);
return 0;
}
I started the program with ./teststring -dir=/home/stephen and got:
/home/stephen
�a
I was expecting both outputs to be the same.
The program has undefined behavior.
The pointer sdata->dir will be invalid after exiting the function parameters because the object s will not be alive. It has only the block scope of the function.
Also use the operators new and delete instead of calling the C function malloc. So write
sim * sdata = new sim;
You could write within the function for example like
if ( token == "-dir" )
{
sdata->dir = new char[s.length() + 1 ];
strcpy( sdata->dir, s.c_str() );
cout << sdata->dir << endl;
}
else
{
sdata->dir = nullptr;
}
provided that the data member dir is declared without the qualifier const.
typedef struct sim {
char* dir;
} sim;
Also using the typedef specifier in the structure declaration is redundant in C++.
So in main you will need to write
delete [] sdata->dir;
delete sdata;

C++ custom string split?

I am still a newbie to c++; I was wondering why the code i wrote for a custom string split fuction does not work? (it splits by char and not string) I think there is something wrong with memcpy in the second instance?
char** strsplit(const char *s, const char splitboi)
{
const int LEN = length(s);
int segs = 0;
char *segstore, **out;
for (int chrs=0; chrs<=LEN; chrs++)
{
if(*(s+chrs) != splitboi)
{char* temp = chrs==0 ? (char*)"" : segstore;
segstore = new char[chrs+1];
memcpy(&segstore, &temp, sizeof(char*));
segstore[chrs] = *(s+chrs);}
else if(*(s+chrs) == splitboi)
{char **temp = out;
out = new char* [segs+1];
memcpy(&out, &temp, sizeof(char**)); //something wrong with this
out[segs] = segstore;
segs++;}
}
delete segstore;
cout << out[0] << '\n';
return out;
}

Own strncpy() C++

I am trying to implement my own version of strncpy(), i found a source code from this link.
But I encountered a Unhandled exception at 0x00411ad5 in exercise 2.exe: 0xC0000005: Access violation writing location 0x00417800. everytime the code reaches this code while((x++ < n) && (*dest++ = *source++));
Here is the complete code:
char *strncpy(char * destination, const char * source, size_t n){
char *dest;
dest = destination;
size_t x=0;
while((x++ < n) && (*dest++ = *source++)); //this is where unhandled exception occurs
while(x++ < n){
*dest++ = 0;
}
return dest;
}
int main(){
char *sample = "blue";
char * sample2 = "red";
cout << strncpy(sample, sample2, 5);
getch();
return 0;
}
Please tell me why this occurs and how should I fix it? Thanks!
Your destination is "blue" which is a string literal, that is a constant. As such it is located in a read-only part of memory (and pointed at by local sample variable), thus error when writing.
Try this:
int main(){
char sample[] = "blue";
char * sample2 = "red";
cout << strncpy(sample, sample2, 5);
getch();
return 0;
}
which makes sample an array in local, writeable memory.
You cannot write to a string constant (sample); write to a char array instead:
int main(){
char *sample = "blue";
char buffer[5];
cout << strncpy(buffer, sample, sizeof(buffer));
getch();
return 0;
}
First, it was already explained to you that you can't overwrite a string that is defined like that.
Second, you cant use cout << strncpy if that function returns pointer to the end of the copied string.
There are two main problems with your program
The first one is that function strncpy has to return destination instead of dest
char *strncpy(char * destination, const char * source, size_t n){
char *dest;
dest = destination;
size_t x=0;
while((x++ < n) && (*dest++ = *source++)); //this is where unhandled exception occurs
while(x++ < n){
*dest++ = 0;
}
// return dest;
return destination;
}
The second one is that string literals are immutable. Any attempt to modify a string literal results in undefined behaviour.
Thus main function should be rewritten the following way
int main(){
char sample[] = "blue";
char * sample2 = "red";
cout << strncpy(sample, sample2, sizeof( sample ) );
getch();
return 0;
}
Also it is a bad style of programming to use variable with name x as a count. It is better to use for example i.
I would write the function simpler
char * strncpy( char *destination, const char *source, size_t n )
{
char *dest = destination;
while ( n-- && ( *dest++ = *source++ ) );
while ( n-- ) *dest++ = '\0';
return destination;
}

I'm trying to create my own strcat() function instead of implementing the one using the <cstring> library

//this is my own function, when i call it nothing shows up on the screen
char * strcat1(char * destination, const char * value)
{
while(*destination != '\0')
destination++;
while(*value != '\0')
{
*destination = *value;
destination++;
value++;
}
*destination = '\0';
return destination;
}
The problem is that the function returns pointer to the terminating zero of the string pointed to by pointer destination.
The correct function can look the following way
char * strcat1(char * destination, const char * value)
{
char *p = destination;
while ( *p != '\0' ) ++p;
while( *p++ = *value++ );
return destination;
}
You can use it the following way
char string3[30] = "this is done";
char string4[] = " using pointers";
puts( strcat1( string3, string4 ) );
puts( string3 );

C Function to reverse char array string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reversing a string in C
I'm currently switching from C++ to C programming for a project and I haven't done much with Char arrays as strings. I need a function that will read in a pointer to a char array and reverse it. I wrote this in C++, which is pretty easy using the string functions, but I'm a little confused on if there are functions or something else in C that is the best way to do this. Thanks, and I'm not necessarily looking for someone to completely finish the code, but to point me in the right direction. If it's simple one line something feel free, but don't do anything that makes you feel uncomfortable.
#include<stdio.h>
#include<string.h>
void reverseString(char *myString)
{
//reverse string here
}
int main(void)
{
char myString[] = "This is my string!";
reverseString(myString);
return 0;
}
Simplest way: Loop the string char by char and insert each char to another char array in the reverse order.
Or try this:
2)
void reverse_string(char str[])
{
char c;
char *p, *q;
p = str;
if (!p)
return;
q = p + 1;
if (*q == '\0')
return;
c = *p;
reverse_string(q);
while (*q != '\0') {
*p = *q;
p++;
q++;
}
*p = c;
return;
}
3)
if( strlen( str ) > 0 ) {
char* first = &str[ 0 ];
char* last = &str[ strlen( str ) - 1 ];
while( first < last ) {
char tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
4)
char* strrev( char* s )
{
char c;
char* s0 = s - 1;
char* s1 = s;
/* Find the end of the string */
while (*s1) ++s1;
/* Reverse it */
while (s1-- > ++s0)
{
c = *s0;
*s0 = *s1;
*s1 = c;
}
return s;
}