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

Edited 5 Years Ago by Moschops: n/a

This question has already been answered. Start a new discussion instead.