-3

code:

#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;
}

The program is running but is not giving result as expected.....I want to swap the position of string in the array *names.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208

1 Answers1

2

First declare as:

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

This is array of char* and now you are to swap addresses of string so pass pass address of address (read comments).

Code:

#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;
}

To understand declaration and code may read figure number one in my this answer: What does the 'array name' mean in case of array of char pointers?

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208