繁体   English   中英

处理C中指向多个字符串的指针数组中存储的单个字符串的问题

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

提供了指向字符串的指针数组作为输入。 任务是反转存储在指针输入数组中的每个字符串。 我制作了一个名为reverseString()的函数,该函数可以反转传递给它的字符串。 据我所知,此功能正常工作。

在指针的输入数组中存储/引用的字符串被一一发送到reverseString()函数。 但是,当使用temp变量交换传递的字符串的值时,代码会在reverseString()函数中的某些地方挂起。 我不知道为什么交换值时代码会挂起。 请帮我解决一下这个。

代码如下:

#include <stdio.h>
void reverseString(char*);

int main()
{   char *s[] = {"abcde", "12345", "65gb"};
    int i=0;
    for(i=0; i< (sizeof(s)/sizeof(s[0]) ); i++ )
    {   reverseString(s[i]);
        printf("\n%s\n", s[i]);
    }

    getch();
    return 0;
}//end main

void reverseString(char *x)
{   int len = strlen(x)-1;
    int i=0; 
    char temp;
    while(i <= len-i)
    {   temp = x[i];
        x[i] = x[len-i];
        x[len-i] = temp;
            i++;
    }
}//end reverseString

您正在尝试更改字符串文字。

字符串文字通常是不可修改的,实际上应该声明为const

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

如果要创建可修改的字符串数组,请尝试以下操作:

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

编译器会自动确定您需要3个字符串,但无法确定每个字符串需要多长时间。 我已经将它们设置为24个字节长。

字符串(“ abcde”等)可以存储在只读存储器中。 因此,当您尝试修改这些字符串时,一切皆有可能。 指向字符串的指针是可修改的。 只是字符串本身不是。

您应该包含<string.h>以获得strlen(3)的声明,并包含另一个标头以获得功能getch() -它不在我的MacOS X系统上的<stdio.h> (因此,我删除了该调用;在Windows上可能是在<stdio.h><conio.h>声明的。

希望这对您有所帮助! 我在这里所做的是,我要转到字符串中最后一个字符的地址,然后通过将指针减少1个单位(对于字符为2个字节(请检查))来打印所有字符。

//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++;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM