问题与存储在指针数组在C多个字符串处理个人字符串 [英] Problem with processing individual strings stored in an array of pointers to multiple strings in C

查看:240
本文介绍了问题与存储在指针数组在C多个字符串处理个人字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

存储的指针的输入数组中引用的串/由一到reverseString()函数发送的一个。但是,code在该reverseString()函数某一点时挂起传递的字符串的值使用临时变量进行交换。我想不通为什么,而交换价值的code挂。请帮我这一点。

在code是如下:

 的#include<&stdio.h中GT;
无效reverseString(字符*);诠释的main()
{字符* S [] = {ABCDE,12345,65GB};
    INT I = 0;
    对于(I = 0; I&≤(sizeof的(多个)/的sizeof(S [0]));我+ +)
    {reverseString(S [I]);
    的printf(\\ n%S \\ N,S [I]);
    }    残培();
    返回0;
} //主到底无效reverseString(字符* X)
{INT LEN = strlen的(X)-1;
    INT I = 0;
    焦温度;
    而(I< = LEN-I)
    {TEMP = X [I];
    X [i] = X [LEN-I];
    X [LEN-I] =温度;
            我++;
    }
} //结束reverseString


解决方案

您正试图改变字符串。

字符串字面通常是不可修改的,真应该被声明为常量

 为const char * S [] = {ABCDE,12345,65GB};
/ *指向字符串* /

如果你想修改字符串数组,试试这个:

 个char [] [24] = {ABCDE,12345,65GB};
/ *非只读数组从字符串初始化* /

,编译器将自动确定需要3弦,但它不能确定每个需要多久可以。我做了他们24个字节长。

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 reverseString() which reverses the string passed to it. This functions works correctly as far as i know.

The strings stored/referenced in the input array of pointers are sent one by one to the reverseString() function. But the code hangs at some point in the reverseString() function when the values of the passed string are swapped using a temp variable. I can't figure out why the code is hanging while swapping values. Please help me with this.

The code is as follows:

#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

解决方案

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.

这篇关于问题与存储在指针数组在C多个字符串处理个人字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆