I have a 2d array of words.
void main() { const int rowsCount = 2; const int colsCount = 5; char*** szData = new char** [rowsCount]; //Allocate memory for each row for (int i = 0; i < rowsCount; i++) { szData[i] = new char* [colsCount]; //how many words in every row for (int j = 0; j < colsCount; j++) { szData[i][j] = new char[15]; //maximum symbols in a word } } //Assign some data for (int i = 0; i < rowsCount; i++) { char s[] = "Williams"; szData[i][0] = s; sprintf(szData[i][0], "Williams%d", 0); sprintf(szData[i][1], "J.%d", 0); sprintf(szData[i][2], "#3%d", 0); sprintf(szData[i][3], "100%d", 0); sprintf(szData[i][4], "01.13%d", 0); } ... } While assigning data, I tried to change this
sprintf(szData[i][0], "Williams%d"); to this
char s[] = "Williams"; szData[i][0] = s; Why do I keep getting the message that my project "has trigerred a breakpoint"?
Is there any alternative to sprintf using array of characters? Cannot use string (one of the condition of this task)
Also, not so necessary, but if I delete 0 at the end here
sprintf(szData[i][0], "Williams%d", 0); sprintf(szData[i][1], "J.%d", 0); sprintf(szData[i][2], "#3%d", 0); sprintf(szData[i][3], "100%d", 0); sprintf(szData[i][4], "01.13%d", 0); there will appear some numbers after every word. For example: Williams3937516. Why is that?
Full code:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <iomanip> #include <conio.h> using namespace std; void main() { const int rowsCount = 2; const int colsCount = 5; char*** szData = new char** [rowsCount]; //Allocate memory for each row for (int i = 0; i < rowsCount; i++) { szData[i] = new char* [colsCount]; //how many words in every row for (int j = 0; j < colsCount; j++) { szData[i][j] = new char[15]; //maximum symbols in a word } } //Assign some data for (int i = 0; i < rowsCount; i++) { char s[] = "Williams"; szData[i][0] = s; sprintf(szData[i][0], "Williams%d"); sprintf(szData[i][1], "J.%d", 0); sprintf(szData[i][2], "#3%d", 0); sprintf(szData[i][3], "100%d", 0); sprintf(szData[i][4], "01.13%d", 0); } //print all the elements for (int i = 0; i < rowsCount; i++) { for (int j = 0; j < colsCount; j++) { cout << szData[i][j] << " "; } cout << endl; } //free memory here for (int i = 0; i < rowsCount; i++) { for (int j = 0; j < colsCount; j++) { delete[] szData[i][j]; } } for (int i = 0; i < rowsCount; i++) { delete[] szData[i]; } delete[] szData; }
vectors, to correctly manage all the memory allocations for you, accurately and correctly. The above looks like bug-prone C code instead of C++. Modern C++ rarely needs to usenewordelete. There's some kind of a bug in the shown code regarding memory allocation, but rather than wasting time trying to figure out what it is, a much simpler solution is to make it logically impossible for this kind of a bug to happen. Scrap everything, and rewrite it from scratch using modern C++ container and iterator-based code.vectoryet, unfortunately (another condition of the task)