c++ - How can I quickly printf 2 dimensional array of chars made of pointers to pointers without using a loop? -
i'm making ascii game , need performance, decided go printf(). there problem, designed char array multidimensional char ** array, , printing outputs garbage of memory instead of data. know it's possible print loop performance rapidly drops way. need printf static array[][]. there way?
i did example of working , notworking array. need printf() work nonworking array.
edit: using visual studio 2015 on win 10, , yeah, tested performance , cout slower printf (but don't know why happening)
#include <iostream> #include <cstdio> int main() { const int x_size = 40; const int y_size = 20; char works[y_size][x_size]; char ** notworking; notworking = new char*[y_size]; (int = 0; < y_size; i++) { notworking[i] = new char[x_size]; } (int = 0; < y_size; i++) { (int j = 0; j < x_size; j++) { works[i][j] = '#'; notworking[i][j] = '#'; } works[i][x_size-1] = '\n'; notworking[i][x_size - 1] = '\n'; } works[y_size-1][x_size-1] = '\0'; notworking[y_size-1][x_size-1] = '\0'; printf("%s\n\n", works); printf("%s\n\n", notworking); system("pause"); }
note: think make kind of buffer or static array copying , displaying data, wonder if can done without it.
if print 2d structure printf
without loop, need present printf
contiguous one-dimension c string. since game needs access string 2d structure, make array of pointers flat structure this:
array of pointers partitions buffer use 2d structure, while buffer can printed printf
because contiguous c string.
here same structure in code:
// x_size+1 '\n's; overall +1 '\0' char buffer[y_size*(x_size+1)+1]; char *array[y_size]; // setup buffer , array (int r = 0 ; r != y_size ; r++) { array[r] = &buffer[r*(x_size+1)]; (int c = 0 ; c != x_size ; c++) { array[r][c] = '#'; } array[r][x_size] = '\n'; } buffer[y_size*(x_size+1)] = '\0'; printf("%s\n", buffer);
Comments
Post a Comment