[Solved] C++ copying char to a char array (Debug assertion failed) says string is not null terminated


strcat() (which is a “less-safe” version of strcat_s()) requires both strings to be null-terminated. That’s because strcat() appends its second parameter (source) where first parameter (dest) ends. It replaces null-terminator of dest with first character of source, appends rest of source and then

a null-character is included at the end of the new string formed by
the concatenation of both

I would simply change

strcpy_s(TeamList[0], Team1);
strcat_s(TeamList[1], Team2);
strcat_s(TeamList[2], Team3);
strcat_s(TeamList[3], Team4);
strcat_s(TeamList[4], Team5);

to

strcpy_s(TeamList[0], Team1);
strcpy_s(TeamList[1], Team2);
strcpy_s(TeamList[2], Team3);
strcpy_s(TeamList[3], Team4);
strcpy_s(TeamList[4], Team5);

strcpy_s() does not have any requirements regarding contents of destination – only its capacity matters.

If you want to stick with strcat_s(), do this:

char TeamList[5][7];
memset(TeamList, 0, sizeof(char) * 5 * 7);

Then, this line:

TeamList[5][7]= '\0';

is not required, It is incorrect anyway, because for N-element array valid indexes are [0; N-1].

EDIT

Since in your case swapping comes into play, I would suggest you totally different approach.

First of all:

#include <string>

Then, initialize teams this way:

std::string TeamList[] =
{
  "Grubs",
  "Giants",
  "Bulls",
  "Snakes",
  "Echos"
};

Now, TeamList is an array containing 5 elements and each of these elements is an object of type std::string, containing name of a particular team.

Now, if you want to swap, let’s say, teams 1 and 3:

std::swap(TeamList[1], TeamList[3]);

std::swap() is a standard C++ function extensively used in standard library implementation. It is overloaded for many standard types, including std::string. This solution has one, critical benefit: if string’s content is held on the heap, swapping two strings is as simple as swapping pointers (and some length/capacity variables).

Oh, and one more thing: if you are not familiar with std::string and you would need to get pointer to a buffer containing string’s data, you can do it this way:

const char* team_1_raw_name = TeamList[0].c_str();

See this page for more info about std::string

7

solved C++ copying char to a char array (Debug assertion failed) says string is not null terminated