How Do You Create a Char Array with Other Variables?◀ Advanced▶ A List of Traps and Tips Amazon
f you use C, a need may arise where you want to create a global char array from other variables. The following is sample code showing how you normally create a global string variables:
// use fileName
// use fileNameFace
As you can see, someFunction
can use fileName
are global variables.
However, suppose you want to change the folder from image
, you will need to manually change the value of fileName
and that of fileNameFace
. While doing so may not be much of a hassle, consider the case where you have 10 such strings. Changing 10 string variables can be a hassle.
So question is: How can you extract the folder name and make it a variable?
If you can do that, you will only need to change the value of one variable instead of 10.
Declare a macro
#define createString(s1, s2, s3) sprintf(s1, "D:\\%s\\%s.bmp", s2, s3);
This macro allows you to construct a string, aka a char array, from two other strings.
Declare the strings you need
In my example, I need the following strings. Declare them at the top of your source code below the macro. Declare more if you need more.
The char array variable imageDir
is for you to put the name of the image folder.
Create strings in the beginning of main()
In the beginning of your main() function, write the following code:
createString(fileName, imageDir, "original");
createString(fileNameFace, imageDir, "face");
That's it! Next time suppose you want to change the folder from image
, simply manually change the following line of code:
And recompile and run the program and fileName
, and all other variables you may have declared will be updated with the new folder automatically. One manual change is all you need to update all the related char array variables. How nice!◀ Advanced▶ A List of Traps and Tips