How to copy string from a single dimensional array to 2d array in c?

-1

I am trying to copy same characters from an single dimensional char array to each row of a 2d array,but I cant any output.

Expected output:

            abcd  
            abcd  
            abcd  
            abcd   

Output I got:

process returned -1073741819(0xC0000005) execution time : 4.583s  
press any key to continue  

Here's the code:

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

void main()
{
    int i,j;
    char v[4]={'a','b','c','d'};
    char answers[10][10];
    for(i=0;i<4;i++){
        for(j=0;j<4;j++){
            strcpy(answers[i][j],v[i]);
        }
    }
    for(i=0;i<4;i++){
        printf("\n%s",answers[i]);
    }
    getch();
}
c
arrays
string
asked on Stack Overflow Nov 14, 2019 by alvin lal • edited Nov 15, 2019 by Blaze

2 Answers

3

Strings in C are null-terminated. Try this instead:

char v[5] = { 'a','b','c','d', '\0' };

Also this here

for(i=0;i<4;i++){
    for(j=0;j<4;j++){
        strcpy(answers[i][j],v[i]);
    }
}

Doesn't work because you're trying to copy characters, but this function expects strings. Your compiler should issue a warning about incompatible types. Replace this nested loop with this:

for (i = 0; i < 4; i++) {
    strcpy(answers[i], v);
}
answered on Stack Overflow Nov 14, 2019 by Blaze
2

You are using

strcpy(answers[i][j],v[i]);

but, neither answers[i][j] nor v[i] is a string (or, pointer to a char array). You're essentially accessing out of bound memory, thereby invoking undefined behaviour.

Solution: You can simply use the assignment operator =, to copy each element one by one.

That said, if you want to use the answers[i] as string, (as seen in printf("\n%s",answers[i]);) you need to make sure it's null-terminated. A quick way of achieving that would be to initialize the array to 0 upon definition.

Something like

 char answers[10][10] = {0};  // ensure the elements are zero-initialized
answered on Stack Overflow Nov 14, 2019 by Sourav Ghosh • edited Nov 14, 2019 by Sourav Ghosh

User contributions licensed under CC BY-SA 3.0