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
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.
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]);
Related
Trying to take a lower case string, and create a new string after making characters uppercase
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
string word = "science";
char new_word[] = {};
for (int i = 0, len = strlen(word); i < len; i++)
{
if (islower(word[i]))
{
new_word = new_word + toupper(word[i]);
}
}
}
I am getting "error: array type 'char[0]' is not assignable".
This isn't all, and I am sure with my full program there might be an easier way, but I built out everything else, and the only point that I am struggling with is looping through my string to get a new word that is uppercase.
Any assistance would be greatly appreciated!
char new_word[] = {};
Your new char array has length 0 and any access invokes undefined behaviour (UB) as you access it outside its bounds.
If your compiler supports VLAs:
string word = "science";
char new_word[strlen(word) + 1] = {0,};
if not:
string word = "science";
char *new_word = calloc(1, strlen(word) + 1);
and
new_word[i] = toupper((unsigned char)word[i]);
If you used calloc do not forget to free the allocated memory
Undefined behavior when word[i] < 0
Avoid that by accessing the string as unsigned char
As per C reference about toupper()
int toupper( int ch );
ch - character to be converted. If the value of ch is not representable as >unsigned char and does not equal EOF, the behavior is undefined.
This is not correct, compiler gives error , "error: assignment to expression with array type"
new_word = new_word + toupper(word[i]);
which is not allowed with an array type as LHS of assignment.
changed to
new_word[i] = toupper((unsigned char)word[i]);
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
char word[] = "science";
char new_word[sizeof word] = "";
int i;
for (i = 0; i < sizeof(word); i++)
{
if (islower(word[i]))
{
new_word[i] = toupper(word[i]);
}
else /* for Upper case latter, simply fill the array */
{
new_word[i] = word[i];
}
}
new_word[i] = '\0';
printf("%s", new_word);
}
OUTPUT:
SCIENCE
EDIT:
Just echo comment from solution given by M.M and comment from
David C. Rankin casting is not necessary for this example. read comment below from M.M and David C. Rankin
Removed unsigned char from islower() and toupper()
This is but one way of accomplishing the task. Make sure to come up with your way of doing.
#include <stdio.h>
#include <string.h>
#define MAX_BUFF 128
char *upperCase(char *c) {
//printf("%s, %d", c, strlen(c));
for(int i=0; i<strlen(c) && i<MAX_BUFF; i++) {
c[i] = c[i] - ' '; // convert char to uppercase
//printf(">> %c", c[i]);
}
return c;
}
int main (void)
{
char word[MAX_BUFF] = "science";
char new_word[MAX_BUFF];
printf("in>> %s \n", word);
strcpy(new_word, upperCase(&word[0]));
printf("out>> %s\n", new_word);
}
Output:
in>> science
out>> SCIENCE
Named arrays cannot be resized in C, you have to set the size correctly to start:
size_t len = strlen(word);
char new_word[len + 1]; // leaving room for null-terminator
Note that no initializer can be used for new_word when its size was determined by a function call (a lame rule but it is what it is); and you can take out the len loop variable since it is now defined earlier.
Then set each character in place:
new_word[i] = toupper(word[i]);
but be careful with the surrounding if statement: if that were false, then you need to set new_word[i] = word[i] instead.
(Pro tip, you can get rid of the if entirely, because toupper is defined to have no effect if the character was not lower case).
Lastly, there should be a null terminator at the end:
new_word[len] = 0;
NB. To be technically correct, the call to toupper should be: toupper((unsigned char)word[i]) -- check the documentation of toupper to understand more about this.
Write a function common_char that takes two strings as arguments and returns a new string that contains a single copy of all characters that appear in either of the two strings.
For example, string1: hello; string2: world; the new string is : hellowrd (o and l were already in array from hello).
May use string function here.In other words, all characters in string1 are copied into the new string, but characters in string 2 are copied only characters that are not in string1. That is past exam question and the university did not provide answer. Here is my code.
#include <stdio.h>
#include <string.h>
char *common_char(char *string1, char *string2) {
int str_length1 = strlen(string1);
int str_length2 = strlen(string2);
char *new_string = malloc(str_length1+str_length2+1);
for (int index_1 = 0; index_1 < str_length1; index_1++) {
for (int index_2 = 0; index_2 < str_length2; index_2++) {
if (string1[index_1] == string2[index_2]) {
}
}
}
}
int main(void) {
return 0;
}
My idea is to find duplicate characters in string 2 and string 1 according to the nested loop, but there is a problem with the conditional statement, there is red line, also how to copy the character of the non-duplicate string? I know strcopy(), but how to remove the repeated characters?
I've come up with a solution that uses dynamic memory and resizes the result char* each time a new char must be added. There are two loops, the first iterates the b string and the second loop checks that non of char of the b string is repeated in the a string, if it is not repeated, then adds it. Hope you understand the realloc to resize dynamically the char* each time it must be added an element.
Firstly I initialize the result string to the size of string a so it can be all copied inside. The ordering method I think it is called bubble method.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* common_char(char* a, char* b) {
char* result = (char*)malloc(sizeof(char)*strlen(a)+1);
int i = 0;
int j = 0;
int repeated = 0;
strcpy(result,a);
for(i=0; i<strlen(b); i++) {
for(j=0; j<strlen(result); j++) {
if(b[i] == a[j]) {
repeated = 1;
}
}
if(!repeated) {
result = (char*)realloc(result,strlen(result)+sizeof(char));
result[strlen(result)] = b[i];
result[strlen(result)+1] = '\0';
}
repeated = 0;
}
return result;
}
int main()
{
char a[] = "hello";
char b[] = "world";
char* result = common_char(a,b);
printf("%s", result);
return 0;
}
EDIT: I've modified the code to make it function. About the comment of memory allocation, I've modified the declaration of result to give it space for the '\0'. When doing the realloc, I've already considered that the realloc does not increment the strlen() because strlen() is a counter till the '\0' not of the size of the variable.
I am trying to reverse a string. scanf is working well but when I use fixed string then it gives garbage value. So where is the fault ?
#include<stdio.h>
#include<string.h>
int main()
{
char s[50]="Hi I Love Programming";
char rev[strlen(s)];
int i,k;
k=strlen(s);
for(i=0; i<strlen(s); i++)
{
rev[k]=s[i];
k--;
}
printf("The reverse string is: %s\n", rev);
}
Your program has two issues:
1.
char rev[strlen(s)];
You forgot to add an element for the string-terminating null character '\0'.
Use:
char rev[strlen(s) + 1];
Furthermore you also forgot to append this character at the end of the reversed string.
Use:
size_t len = strlen(s);
rev[len] = '\0';
Note, my len is the k in your provided code. I use the identifier len because it is more obvious what the intention of that object is. You can use strlen(s) because the string has the same length, doesn´t matter if it is in proper or reversed direction.
2.
k=strlen(s);
for(i=0; i<strlen(s); i++)
{
rev[k]=s[i];
k--;
}
With rev[k] you accessing memory beyond the array rev, since index counting starts at 0, not 1. Thus, the behavior is undefined.
k needs to be strlen(s) - 1.
Three things to note:
The return value of strlen() is of type size_t, so an object of type size_t is appropriate to store the string length, not int.
It is more efficient to rather calculate the string length once, not at each condition test. Use a second object to store the string length and use this object in the condition of the for loop, like i < len2.
char s[50]="Hi I Love Programming"; can be simplified to char s[]="Hi I Love Programming"; - The compiler automatically detects the amount of elements needed to store the string + the terminating null character. This safes unnecessary memory space, but also ensures that the allocated space is sufficient to hold the string with the null character.
The code can also be simplified (Online example):
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[] = "Hi I Love Programming";
size_t len = strlen(s);
char rev[len + 1];
size_t i,j;
for(i = 0, j = (len - 1); i < len; i++, j--)
{
rev[j] = s[i];
}
rev[len] = '\0';
printf("The reverse string is: %s\n", rev);
}
Output:
The reverse string is: pgnimmargorP evoL I iH
your program is hard to understand. Here you have something much simpler (if you want to reverse the string of course)
#include <stdio.h>
#include <string.h>
char *revstr(char *str)
{
char *start = str;
char *end;
if(str && *str)
{
end = str + strlen(str) - 1;
while(start < end)
{
char tmp = *end;
*end-- = *start;
*start++ = tmp;
}
}
return str;
}
int main()
{
char s[50]="Hi I Love Programming";
printf("%s", revstr(s));
}
https://godbolt.org/z/5KX3kP
I made a c program that attempts to add the values of one string array to another using a separate method:
#include <stdio.h>
#include <stdlib.h>
void charConv(char *example[])
{
example= (char* )malloc(sizeof(char[4])*6);
char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
printf("flag\n");
int i;
i=0;
for(i=0; i<6; i++){
strcpy(example[i], y[i]);
}
}
int main() {
char *x[6];
charConv( *x[6]);
printf("%s\n", x[0]);
}
However it keeps returning a segmentation fault. I'm only beginning to learn how to use malloc and c in general and its been puzzeling me to find a solution.
To pin-point your problem: you send *x[6] (here - charConv( *x[6]);) which is the first char of the 7'th (!!!) string (Remember, C is Zero-Base-Indexed) inside an array of 6 string you didn't malloc -> using memory you don't own -> UB.
Another thing I should note is char[] vs char * []. Using the former, you can strcpy into it strings. It would look like this:
'c' | 'a' | 't' | '\0' | 'd' | 'o' | 'g' | ... [each cell here is a `char`]
The latter ( what you used ) is not a contiguous block of chars but a array of char *, hence what you should have done is to allocate memory for each pointer inside your array and copy into it. That would look like:
0x100 | 0x200 | 0x300... [each cell is address you should malloc and then you would copy string into]
But, you also have several problems in your code. Below is a fixed version with explanations:
#include <stdio.h>
#include <stdlib.h>
void charConv(char *example[])
{
// example= (char* )malloc(sizeof(char[4])*6); // remove this! you don't want to reallocate example! When entering this function, example points to address A but after this, it will point to address B (could be NULL), thus, accessing it from main (the function caller) would be UB ( bad )
for (int i = 0; i < 6; i++)
{
example[i] = malloc(4); // instead, malloc each string inside the array of string. This can be done from main, or from here, whatever you prefer
}
char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
printf("flag\n");
/* remove this - move it inside the for loop
int i;
i=0;
*/
for(int i=0; i<6; i++){
printf("%s\t", y[i]); // simple debug check - remove it
strcpy(example[i], y[i]);
printf("%s\n", example[i]); // simple debug check - remove it
}
}
int main() {
char *x[6];
charConv( x); // pass x, not *x[6] !!
for (int i = 0; i < 6; i++)
{
printf("%s\n", x[i]); // simple debug check - remove it
}
}
As #MichaelWalz mentioned, using hard-coded values is not a good practice. I left them here since it's a small snippet and I think they are obvious. Still, try to avoid them
You need to start by understanding the pointers and some other topics as well like how to pass an array of strings to a function in C etc.
In your program, you are passing *x[6] in charConv() which is a character.
Made corrections in your program -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void charConv(char *example[], int num)
{
int i;
for (i = 0; i < num; i++){
example[i] = (char* )malloc(sizeof(char)*4);
}
const char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
for(i = 0; i < num; i++){
strcpy(example[i], y[i]);
}
}
int main() {
char *x[6];
int i = 0;
charConv(x, 6);
/* Print the values of string array x*/
for(i = 0; i < 6; i++){
printf("%s\n", x[i]);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * reverse(char *string);
int main(int argc, char *argv[])
{
char array[10];
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = 'd';
array[4] = 'e';
printf("1%s\n",array);
char *p = reverse(array);
printf("4%s\n",p);
printf("5%s\n",array);
}
char * reverse(char *string)
{
int size = strlen(string);
char reversed[size];
int i;
int j = 0;
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
printf("2%s\n",reversed);
string = reversed;
printf("3%s\n",string);
return reversed;
}
This code basically just initializes an array of values and passes it into a method that reverses these values.
I am not sure if this is the best way to execute the task, since I am new to pointers and arrays in C.
But the real question is this:
Can anyone figure out why in this line
printf("4%s\n",p);
if you remove the preceding '4', so it looks like so
printf("%s\n",p);
the line won't print at all?
You are returning a pointer to local variable(reversed) in the function reverse the question should actually be: Why did it work in the first place?.
This code string = reversed; will only copy the pointer, and again the local copy of the pointer so it has no effect outside the function.
To reverse a string you don't need additional memory - this can be done in-place.
Strings in C must end with the null character. You're using strlen on a non null-terminated string.
Furthermore, you just a very lucky person, because there is a serious problem with you code: you forget to add \0 symbol at the end of string.
UPD: the main problem is with code line char reversed[size];.
It's a regular local variable, it has automatic duration, which means that it springs into existence when the function is called and disappears when the function returns (see this link).
You need to change it to:
char *reversed = malloc((size+1)*sizeof(char));
UPD-2: another bug fixing will be:
1) add array[5] = '\0'; after all other array initializing lines
2) add reversed[j] = '\0'; after for...loop:
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
reversed[j] = '\0';
UPD-3: But in general it will much more correctly initialize your string in appropriate way:
char array[10] = "abcde";