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

int main(void)
{
string s = get_string("Enter a number: ");
string answer = 0

for (int i = 0, n = strlen(s); i < n; i++)
{

    int min_value = 0;
    for (int j = i; j < (n - i); j++)
    {
        min_value = s[i];
        if (min_value > s[j])
        {
            min_value = s[j];
        }
        else
        {
            min_value = s[i];
        }

    }

    answer[i]= min_value;
}

printf("%s", answer);
}

The program compiles, but I get a runtime error. What could be the issue? Been scratching my head for hours, can't figure it out. While trying to tackle this problem, I found a lot of holes in my understanding of arrays and strings, could someone explain that as well?

1 Answer 1

2

The main problem is in the following statements:

string answer = 0; 
answer[i]= min_value;

Let's see if I can explain it clearly; a variable of type string is really a typedef (an alias in other words) of char *, that is, a pointer to a char, the first of the previous statements assigns a null (zero) pointer to answer, the second statement tries to dereference a null pointer (during the execution) which is not allowed, with which we get an error. The problem with variables of type string goes even further, to this type e variables should only be accessed in read mode, if we have a string such as:

string answer = "abcd \ 0";

and try to change in the program one of the characters with

answer [0] = 'e';

what we get is a segmentation fault, in short the strings can not be changed.

The solution could be to use functions such as malloc or calloc. But I think that at this point of the course it is much easier to use an array, we can not change its length but its content. There are other problems in the code, but this should serve to start

1
  • But when I start to use arrays, I cannot seem to define the length because it won't accept a variable as a viable length. Currently I'm experimenting with command line arguments, let's see where that takes me. Anyhow, thanks for your answer! Jul 9, 2018 at 13:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .