我想從數組中隨機選擇一個字符,將它連接到字符串"array_"
,然後使用新字符串引用數組。如何使用連接兩個動態字符串生成的字符串動態引用數組?
例如,從temp_holder[]
中挑選字符'8'
,將其連接到"array_"
,並用它來引用array_8[][]
。
下面是代碼:
#include <stdio.h>
main() {
int i, j;
char array_8[5][4];
//Array
for (i = 0; i < 5; i++) {
for (j = 0; j < 4; j++) {
array_8[i][j] = 'x';
if ((i == 1 && j == 1) || (i == 1 && j == 2) || (i == 3 && j == 1) || (i == 3 && j == 2)){
array_8[i][j] = ' ';
}
}
}
char myArray[5][4];
//Array
for (i = 0; i < 5; i++) {
for (j = 0; j < 4; j++) {
myArray[i][j] = 'x';
if ((i == 1 && j == 1) || (i == 1 && j == 2) || (i == 3 && j == 1) || (i == 3 && j == 2)){
myArray[i][j] = ' ';
}
}
}
char temp_holder[6] = {'8', '8', '8', '8', '8'};
srand(time(NULL));
int r = rand() % 6;
char arrName[1][10] = {"array_"};
char namesArr[10];
strcpy(namesArr, "array_");
int len = 7;
char arr_names[5][4];
printf("\n%c\n", temp_holder[r]);
strcat(namesArr, &temp_holder[r]);
printf("\n%s\n", namesArr);
strncpy(arr_names, namesArr, len);
strcat(arr_names, "\0");
printf("\n%s\n", arr_names);
int accEntry = 0; //Correct entry counter
for (i = 0; i < 5; ++i){
for (j = 0; j < 4; j++)
if (myArray[i][j] == arr_names[i][j]){
printf("\n MATCH FOUND %c\n", arr_names[i][j]);
accEntry++;
}
}
printf("\n\n\n%d\n\n\n", accEntry);
getchar();
}
變量名稱是程序員,而不是程序。 – Lundin