0

I have exercise to use for loop to initialization 1 string array from A to Z and then Z to A.

I was successful to print from A to Z but print Z to A not working. So i need to help in this code.

char *problem58()
{
    char temp, *result = (char *)malloc(52 * sizeof(char));
    int left = 0, right = 52 - 1;

    for (char i = 'A'; i <= 'Z'; i++)
    {
        result[left] = i;
        printf("%c", i);
        left++;
    }
    // this is my idea to reverse this string
    for (int i = left; i < right; i++)
    {
        temp = result[left];
        result[left] = result[right];
        result[right] = temp;
        printf("%c", result[right]);
        right--;
    }
    return result;
}

line code run in terminal: ABCDEFGHIJKLMNOPQRSTUVWXYZSW\:C=cepSmoC

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Dinosour
  • 45
  • 3
  • 1
    possibly similar to https://stackoverflow.com/questions/784417/reversing-a-string-in-c – Manish Kumar Jun 25 '23 at 10:41
  • `result[left] = result[right];` - what have you assigned to `result[right]` at that point? It looks uninitialized to me. – Ted Lyngmo Jun 25 '23 at 10:49
  • 1
    Also, avoid magic numbers like `52`. Make it `size_t len = ('Z'-'A' + 1) * 2;` and use `len` instead. Another detail: Since you return a pointer to this array, perhaps you should null terminate the array just in case it's meant to be printed? – Ted Lyngmo Jun 25 '23 at 10:51
  • How many times do you write to each location in result? – stark Jun 25 '23 at 12:17

2 Answers2

0

Here is my answer

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

char* problem58()
{
    int n = 0;
    int left = 0, right = 52 - 1;

    // A--->Z and Z--->A total number is 52, because string end with '\0'(0), so add 1 is 53.
    char* result = (char*)malloc(53 * sizeof(char));

    // Check if it is possible to dynamically allocate memory for 53 variables of type "char"
    // You can also write like this: if(result == NULL)
    if(NULL == result){
        printf("No space\n");
        exit(1);
    }

    // Initial result with 0,because string end with ('\0')0.
    // So result[0] will be 0, result[1] will be 0 ...... result[52] will be 0
    for(int m = 0; m < 53;m++){
        result[m] = 0;
    }

    for (char i = 'A'; i <= 'Z'; i++)
    {
        result[left] = i;
        //printf("%c", i);
        left++;
    }

    // Now left is 26, reset it to 0, because result[0] is 'A'
    left = 0;

    // n is execute times, need to let result[51] = result[0] = 'A', and result[50] = result[1] = 'B' ......
    //so right-- and left++
    for (n = 0; n < 26; n++)
    {
        result[right] = result[left];
        right--;
        left++;
    }
    return result;
}

int main()
{

    char* str = problem58();
    printf("str's length is %ld\n",strlen(str));
    printf("%s\n",str);
    free(str);
    return 0;
}

Run it will output

str's length is 52
ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA
Tom
  • 417
  • 3
  • 10
-1

This for loop

for (int i = left; i < right; i++)
{
    temp = result[left];
    result[left] = result[right];
    //..

invokes undefined behavior because the dynamically allocated array was not initialized and as a result the expressions result[left] and result[right] have indeterminate values. There is nothing to swap in the array. The array has to be filled with characters.

Also the array in any case does not contain a string because it is not appended with the terminating zero character '\0';.

If I have understood the assignment correctly then you need something like the following. Pay attention to that the function can be implemented in different ways.

For example

char * problem58( void )
{
    char *s = malloc( 2 * ( 'Z' - 'A' + 1 ) + 1 );

    if ( s != NULL )
    {
        char *p = s;
        char c = 'A';

        do
        {
            *p++ = c;
        } while ( c++ != 'Z' );

        while ( c != 'A' )
        {
            *p++ = --c;
        }

        *p = '\0';
    }

    return s;
}
   

or

char * problem58( void )
{
    size_t n = 2 * ( 'Z' - 'A' + 1 );

    char *s = malloc( n + 1 );

    if (s != NULL)
    {
        char *first = s, *last = s + n;

        *last = '\0';

        char c = 'A';

        do
        {
            *first++ = *--last = c;
        } while (c++ != 'Z');
    }

    return s;
}

     

And the function is called in main like

char *s = problem58();

if ( s != NULL ) puts( s );

free( s );

The expected output of a call of the function is

ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Re “invokes undefined behavior because… indeterminate values”: Using indeterminate values does not, by itself, cause undefined behavior. They are different things with different consequences. – Eric Postpischil Jun 25 '23 at 12:44
  • @EricPostpischil From the C Standard "1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements" – Vlad from Moscow Jun 25 '23 at 12:54
  • That is from Annex J.2, which is a non-normative summary (it is not part of the official standard). It is incorrect on this point; the normative text (which is the official standard) does not make use of indeterminate values undefined behavior. – Eric Postpischil Jun 25 '23 at 14:00
  • @EricPostpischil Relative to building the string his function has undefined behavior because it uses erroneous data. For example the function can build the expected string if the memory used by the allocated array already contains required data. – Vlad from Moscow Jun 25 '23 at 14:15
  • @EricPostpischil And the quote I provided defines the general notion of undefined behavior. – Vlad from Moscow Jun 25 '23 at 14:17