N
N
nikitosssguy2014-04-27 13:21:28
C++ / C#
nikitosssguy, 2014-04-27 13:21:28

Implementation of the analogue of strcat () in c ++

Hello. I am a beginner in c ++ programming, and in the training literature I met the task of writing my own analogue of the strcat () function. I accepted the challenge and this is what happened:

#include <iostream>
#include <cstdio>
#include "stdafx.h"
#include "conio.h"

using namespace std;

void add(char *some, char *some2);
int main(){
  setlocale(0, "");
  char some[80] = "Слово";
  char some2[80] = "Второе";
  add(some, some2);
  cout << some << "\n";
  system("pause");
  return 0;
}
void add(char *some, char *some2){
  int first_length = strlen(some);
  for (int i = 0; i < strlen(some2); i++){
    *(some + first_length + i) = *(some2 + i);
  }
}

I would like to know:
1) How normal is my solution in terms of performance
2) How can I make it shorter and faster
3) And in general, the mistakes I made.
Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2014-04-27
@nikitosssguy

Huge minus - what will happen if the length of some is 79 characters? Where will some2 be copied to?
The second huge minus - what will be the length of the string in the above example after concatenation?
You didn't write a trailing 0 to the resulting string.
The big minus is the recomputation of pointers and the length of some2 in each iteration of the loop. The initial values ​​must be calculated before the loop, only increment / decrement should be done in the loop.
A small minus - it makes no sense to count the length of some2. It is enough just to go to the symbol with code 0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question