0

I've been trying to write a program which would replace all letters in a string with their positions in alphabet. I came up with a code, which appears to be working during debugging but for some reason it won't print the result string.

During debugging string variable in main appears to be correct but it still won't print.

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


char *alphabet_position(char *text) {
    char string[100] = {};
    char temp_c[5] = {};

    int i, temp_i;
    for (i=0; i<strlen(text); i++){
       if (text[i] >= 65 && text[i] <= 90){
                temp_i = text[i] - 'A' + 1;
                snprintf(temp_c, 4, "%d ", temp_i);
                strcat(string, temp_c);


            }
            if (text[i] >= 97 && text[i] <= 122){
                temp_i = text[i] - 'a' + 1 ;
                snprintf(temp_c, 4, "%d ", temp_i);
                strcat(string, temp_c);

            }

        }

return string;



}
int main()
{
    char *string = "The sunset sets at twelve o' clock.";
    char *temp = alphabet_position(string);
    printf("%s" ,temp);
    return 0;
}

Also, I can't really understand why using char *string instead of char string[100] causes segmentation fault during strcat call.

MLapaj
  • 371
  • 3
  • 11
  • MLapaj, Why 100 in `char string[100] = {};`? – chux - Reinstate Monica Aug 06 '19 at 00:22
  • Well, I just put a random so the string would be big enough to contain all the numbers – MLapaj Aug 06 '19 at 00:30
  • Also, how does the post concering variables' scopes answer my question in any way? – MLapaj Aug 06 '19 at 00:34
  • MLapaj, Review [myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.](https://stackoverflow.com/a/4570374/2410359) and see how your code fails the same way. – chux - Reinstate Monica Aug 06 '19 at 00:36
  • Thanks, I did eventually understand how these cases were similar. However what bothers me, is why did debugger show temp in main to be a proper string if it wasn't? And what's more, why did printf in main acutally print the proper string once I added printf("%s", string) before return string in alphabet_positon function? – MLapaj Aug 06 '19 at 08:39
  • MLapaj, "why did debugger show temp in main to be a proper string if it wasn't?" No one says it is not a proper string. "return string;" is _undefined behavior_. What happens after that is _undefined_. Anything may happen. – chux - Reinstate Monica Aug 06 '19 at 12:47

0 Answers0