I feel really dumb asking this, but why does this code print b,b instead of b,a?
the second strcpy() is supposed to copy "a" and put it inside a[1]...

#include <stdio.h>
#include <string.h>


int main(){
    char a[100][100] = {"a","b","c","d"};
    
    char*temp = a[0];
    strcpy(a[0],a[1]);
    strcpy(a[1],temp);
    printf ("%s %s",a[0],a[1]);
    getchar();
    
    
    
    }
char*temp = a[0]; // make a new pointer, and point it at the char in a[0]
strcpy(a[0],a[1]); // Overwrite the char in a[0] with the char in a[1], so now a[0] is 'b'
strcpy(a[1],temp); // overwrite the char in a[1] with temp, which is the char in a[0], which we
                   //   made 'b' in the previous line, so now the char in a[1] is 'b'

If you want to create a temporary copy of a C string, you have to actually copy the characters - just copying the pointer (which is what you're doing) doesn't copy the characters.

#include <stdio.h>
#include <string.h>
#include<stdlib.h>
 
 
int main(){
    char a[100][100] = {"a","b","c","d"};
 
    char* temp = (char*)malloc(sizeof(a[0]) * sizeof(char));
    strcpy(temp, a[0]);
    strcpy(a[0],a[1]);
    strcpy(a[1],temp);
    printf ("%s %s",a[0],a[1]);
    getchar();
			free(temp);
    }

thanks man

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.