使用指针数组中的函数交换字符串位置

时间:2014-01-13 08:04:17

标签: c include char swap names

代码:

#include<stdio.h>                     
int main()
{
    char *names = {"akshay","parag","arun","srinivas","kapil"};     
    printf("Names: %s %s\n",names[1],names[2]); 
    swap(names[1],names[2]);
    printf("Names: %s %s\n",names[1],names[2]);                         
    return 0;
}
swap(char **str1,char **str2)                           
{
    char *t;
    t=*str1;
    *str1=*str2;
    *str2=t;
}

程序正在运行,但没有按预期给出结果.....我想交换数组*names中字符串的位置。

1 个答案:

答案 0 :(得分:2)

首先声明为:

char *names[] = {"akshay", "parag", "arun", "srinivas", "kapil"};  

这是char*的数组,现在您要交换字符串的地址,以便传递地址传递地址(读取注释)。

代码:

#include<stdio.h>
void swap(char **str1,char **str2)                           
{
    char* t =  *str1;   // store address of string-1
    *str1 =  *str2;     // change address of string. 
    *str2 = t;
}
int main()
{
    char *names[] = {"akshay","parag","arun","srinivas","kapil"};     
    printf("Names: %s %s\n", names[1], names[2]); 
    swap(&names[1], &names[2]); // pass address of strings 
    printf("Names: %s %s\n",names[1],names[2]);                         
    return 0;
}

要理解声明和代码,可以在我的答案中读取第一个数字:What does the 'array name' mean in case of array of char pointers?