I
I
iayviyaviyvai2018-10-15 19:18:05
C++ / C#
iayviyaviyvai, 2018-10-15 19:18:05

How to copy a string. Why does it give an error?

Why is this program not compiling? At first the compiler cursed with strcpy, then changed it to strncpy, but it still crashes. Seems strncpylike a safe feature. What is the problem and how to fix it? Should I use strcpy_s?
PS. MSVC

// #define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <cstring>

int main()
{
  const int SIZE = 20;

  const char name[SIZE] = "name";
  char * p_name = new char[SIZE];

  strncpy(p_name, name, SIZE - 1);
  // snprintf(p_name, SIZE, "%s", name);

  system("pause");

  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2018-10-30
@SaNNy32

Should I use strcpy_s?

Yes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question