I have problem with assigning value to string array in c. The code is part of a hangman game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
srand(time(0));
int random = rand() % 5;
char *sWords[] = {"banana", "apple", "GOAT", "jordan", "zhiki"};
printf("%s\n", sWords[random]);
char *sTempWord = sWords[random];
char *sTempArr;
for (int i = 0; sTempWord[i] != '\0'; i )
sTempArr[i] = '_';
for (int i = 0; strlen(sTempArr); i )
printf("%c ", sTempArr[i]);
}
There are no errors, and when I run the program it just exits. The plan is to get random word from the list, create temporary array with the length of the randomly-selected word and assing all elements with value '_'.
Also, when I try to make array with constant value, (like char sTempArr[len]
where len=strlen(sTempWord)
, it says: expression must have a constant value
CodePudding user response:
When declaring an array, the compiler needs to know the length at compile time (e.g. the value can't be a variable).
You can either create an initial empty array with a known number of items (you will need to make sure it's big enough to fit any word from sWords
, including null terminator):
char sTempArr[100];
or you can allocate dynamic memory at runtime with something like malloc()
:
#include <stdlib.h>
int len = strlen(sTempWord) 1; // 1 for '\0'
char *sTempArr; = malloc(len);
// ...
free(sTempArr); // When you are done using the array
They are not the same.
CodePudding user response:
- Not initialized pointer.
char *sTempArr;
- You do not null character terminate the string
for (int i = 0; sTempWord[i] != '\0'; i )
sTempArr[i] = '_';
- As the string is null character terminated you can't call
strlen
for (int i = 0; strlen(sTempArr); i )
printf("%c ", sTempArr[i]);
char sTempArr[strlen(sTempWord) 1];
int i;
for (i = 0; sTempWord[i] != '\0'; i )
sTempArr[i] = '_';
sTempArr[i] = 0;
for (i = 0; strlen(sTempArr); i )
printf("%c ", sTempArr[i]);