0

i have been trying to make a for loop where at i < j. Variable J takes the length of a string to decide how many loops will happen. This works for the first loop, i have debugged and J does get the value of 3 if i put in a string of 3 characters. The problem is that after the first loop J is reset to the value of 0 and i cant seem to figure out why that is. Can anyone help me? Id still call myself a beginner so any advice on code would be appreciated even if its not about my specific question.

#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
string prompt = get_string("Give me a word: " );
int j = strlen(prompt);
char word[] = "";

    for (int i = 0; i < j; i++)
    {
        strcat(word, "p");
    }
    
    printf("%s\n", word);

}
3
  • 5
    With char word[] = ""; you define an array of only a single element (that element being the string null-terminator character '\0'). You can't append to it, any attempt to do so will lead to undefined behavior. Set a large enough size of the array and it should start working, like e.g. char word[j + 1] = ""; Commented Jul 31, 2023 at 12:26
  • 2
    @Someprogrammerdude char word[j + 1] = ""; will not work Commented Jul 31, 2023 at 12:30
  • @0___________ You're correct. Too late to edit now, but correct should be char word[j + 1]; word[0] = '\0';. To explain for other readers: Variable length arrays can not be initialized in place of definition. Setting the first character to the string terminator allows it to be used as a destination for strcat. As for the size, the code adds j number of 'p' characters, plus one for the terminator at the end. Commented Jul 31, 2023 at 12:32

1 Answer 1

3

char word\[\] = ""; I belive that it is typo and it should be

char word[] = "";

You define a char array having one element (null terminating character). When you strcat(word, "p"); you invoke undefined behaviour as you write outside the array bounds. Your array has to be big enough to accommodate all the characters and null terminating character.

int main(void)
{
    string prompt = get_string("Give me a word: " );
    size_t j = strlen(prompt);
    char word[j + 1];

    word[0] = '\0';

    for (int i = 0; j != 0 && i < j; i++)
    {
        strcat(word, "p");
    }
    
    printf("%s\n", word);

}

https://godbolt.org/z/5GPPse96K

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.