1

I have two arrays:

char roundNames1[16][25], roundNames2[16 / 2][25];

I then want to copy a result from the first array to the second. I have tried this:

where roundNames1[5] = "hello"

#include <string.h>

printf("First array: %s", roundNames1[5]);
strcpy(roundNames1[5], roundNames2[6]);
printf("Second array: %s", roundNames2[6]);

But this just returns

First array: hello
Second array:

Why is it not working?

5
  • Yes I noticed this but I also did a test with roundNames2[5] and it didnt work Commented Nov 12, 2014 at 12:09
  • 2
    Also, the parameters to strcpy() should be reversed! Commented Nov 12, 2014 at 12:10
  • @Lundin that is not true Commented Nov 12, 2014 at 13:30
  • Oh sorry you didn't reverse the order of the strcpy parameters, just changed the index to something within array bounds. The strcpy reverse bug is indeed still there, then. Previous comment deleted. Commented Nov 12, 2014 at 13:51
  • @Lundin haha no worries! Commented Nov 12, 2014 at 14:21

3 Answers 3

2

You need to exchange arguments of function strcpy

strcpy( roundNames2[8], roundNames1[5] );

Here is a part pf the function description from the C Standard

7.23.2.3 The strcpy function

Synopsis

1

#include <string.h>
char *strcpy(char * restrict s1, const char * restrict s2);

Description

2 The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

Sign up to request clarification or add additional context in comments.

Comments

1

strcpy - arguments other way around.

http://www.cplusplus.com/reference/cstring/strcpy/

Comments

0

Copy arrays/strings with memcpy

void * memcpy (void * destination, void * source, size_t size)

The memcpy function copies an certain amount of bytes from a source memory location and writes them to a destinaction location. (Documentation)

Example:

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

int main()
{
    char some_array[] = "stackoverflow";

    int memory_amount = sizeof(some_array);
    char *pointer = malloc(memory_amount);
    memcpy(pointer, &some_array, memory_amount);

    printf("%s\n", pointer);

    free(pointer);
    return 0;
}

Output

$ ./a.out 
stackoverflow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.