c - 如何交换两个字符串的第一个字符?两个字符串存储在指针数组中

标签 c arrays string pointers swap

这是我的代码,我在其中创建了一个指针数组。指针数组保存字符串的基地址。我创建了 add 函数,通过该函数将字符串添加到指针数组中。我的座右铭是交换两个字符串“akshay”和“raman”的第一个字符。例如,交换后的“akshay”应变为“rkshay”,交换后的“raman”应变为“aaman”,即 akshay 的 a 应替换为 raman 的 r,反之亦然。 但是,当我执行时,它显示错误,例如“问题导致程序停止正常工作。Windows 将关闭程序并通知是否有可用的解决方案。” 请提供解决方案。

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define MAX 6
char *names[MAX];
int count;
int add(char *);
void swap(int,int);
void show();

int main()
{
 int flag;
 flag=add("akshay");
 if(flag==0)
        printf("unable to add string\n");
        flag=add("parag");
 if(flag==0)
        printf("unable to add string\n");
        flag=add("raman");
 if(flag==0)
        printf("unable to add string\n");
 printf("names before swapping \n");
 show();
 swap(0,2);
 printf("names after swapping \n");
 show();
    return 0;
}
/*adds given string */
int add(char *s)
{
    if(count<MAX)
    {
        names[count]=s;
        count++;
        return 1;
    }
    else return 0;
}
/*swaps the first characters of the two strings */
void swap(int i,int j)
{
    char temp;
    temp=(*names[i]);
    *names[i]=(*names[j]);
    *names[j]=temp;
}
/* displays the elements */
void show()
{
    int i;
    for(i=0;i<count;i++)
    {
        puts(names[i]);
        printf("\n");
    }
}

最佳答案

How can I swap the first character of two strings with each other ?

该函数可以如下所示

void swap( char *s1, char *s2 )
{
    if ( *s1 && *s2 )
    {
        char c = *s1;
        *s1 = *s2;
        *s2 = c;
    }
}

对于您的程序,您正在尝试修改导致未定义行为的字符串文字。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

您应该为每个添加到指针数组的字符串动态分配内存。

当函数依赖全局变量时,这也是一个坏主意。

考虑到根据 C 标准,不带参数的函数 main 应声明为

int main( void )

关于c - 如何交换两个字符串的第一个字符?两个字符串存储在指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042525/

相关文章:

c - 是否可以在 C 中将 char** 转换为 char*?

objective-c - 从函数内的循环返回数字列表

c: strcmp 没有在它应该命中的条件语句处停止

java - 函数返回树的叶子

java - 为什么 String.replace 不起作用?

c - C程序编译警告:assignment makes pointer from integer without a cast [enabled by default]

c++ - 读取文件并删除重复的字母

string - 查找不重复字符的最长子串

string - 在 OCaml 中将字符转换为字符串

c++ - 使用 C++ 方式对结构和数组进行别名处理