top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to swap a character string and character array in C?

+1 vote
501 views

char *p="India";
char t[10]="USA";

after the swap t should contain India and p as USA.

posted Jul 4, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

First of all,
If you have assigned your character pointer as below,

char *p="India";

Then, In that case It is not possible to change the value of *p,
Below is not possible,

p[0]='U';

You can make your pointer to point somewhere else but you can not change value of its.

Now, Coming back to you question,

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
        char *p;
        char t[10]="USA",temp[10];
        p=(char*)malloc(sizeof(char)*10);
        if(p==NULL)
        {
                perror("Malloc Failed : ");
                return;
        }
        strcpy(p,"India");
        printf("p = %s\n",p);
        printf("t = %s\n",t);
        strcpy(temp,t);
        strcpy(t,p);
        strcpy(p,temp);
        printf("After swapping\n");
        printf("p = %s\n",p);
        printf("t = %s\n",t);
}
answer Jul 5, 2016 by Chirag Gangdev
Similar Questions
+2 votes

Output
Enter the string: Welcome to C Class!
Enter the word to insert: programming
Enter the position you like to insert: 3
The string after modification is

Welcome to C programming Class!

0 votes

Enter character: r
Enter string: programming
Output: Positions of 'r' in programming are: 2 5
Character 'r' occurred for 2 times

+1 vote

How to find first unrepeated character in string using C/C++?

Input       Output     
abc         a    
aabcd       b
aabddbc     c
0 votes

Find the first non repeating character in a string.

For example
Input string: "abcdeabc"
Output: "e"

...