Problem with processing individual strings stored in an array of pointers to multiple strings in C

前端 未结 3 1345
無奈伤痛
無奈伤痛 2020-12-22 07:30

An array of pointers to strings is provided as the input. The task is to reverse each string stored in the input array of pointers. I\'ve made a function called reverseStrin

相关标签:
3条回答
  • 2020-12-22 07:39

    You are trying to change string literals.

    String literals are usually not modifiable, and really should be declared as const.

    const char *s[] = {"abcde", "12345", "65gb"};
    /* pointers to string literals */
    

    If you want to make an array of modifiable strings, try this:

    char s[][24] = {"abcde", "12345", "65gb"};
    /* non-readonly array initialized from string literals */
    

    The compiler will automatically determine you need 3 strings, but it can't determine how long each needs to be. I've made them 24 bytes long.

    0 讨论(0)
  • 2020-12-22 07:50

    Hope this helps you! what i am doing here is that i am going to the address of the last character in the string then printing them all by decreasing the pointer by 1 unit (for character its 2 bytes(please check)).

    //program to reverse the strings in an array of pointers
    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char *str[] = {
            "to err is human....",
            "But to really mess things up...",
            "One needs to know C!!"
        };
        int i=0;    //for different strings
        char *p;    //declaring a pointer whose value i will be setting to the last character in 
                    //the respective string
        while(i<3)  
        {
            p=str[i]+strlen(str[i])-1;
            while(*p!='\0')
            {
                printf("%c",*p);
                p--;
            }
            printf("\n");       
            i++;
        }
    }
    
    0 讨论(0)
  • 2020-12-22 07:56

    The strings ("abcde" etc) could be stored in readonly memory. Anything is possible when you try to modify those strings, therefore. The pointers to the strings are modifiable; it is just the strings themselves that are not.

    You should include <string.h> to obtain the declaration of strlen(3), and another header to obtain the function getch() - it is not in <stdio.h> on my MacOS X system (so I deleted the call; it is probably declared in either <stdio.h> or <conio.h> on Windows).

    0 讨论(0)
提交回复
热议问题