-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();
}
Blaze
  • 16,736
  • 2
  • 25
  • 44
alvin lal
  • 138
  • 4
  • 10
  • ``? Which era you're in? – Sourav Ghosh Nov 14 '19 at 11:00
  • my university is still in 1995,:D – alvin lal Nov 14 '19 at 11:04
  • What did your debugger tell you? – Jabberwocky Nov 14 '19 at 11:05
  • You need to study how strings and 1D arrays work before worrying about 2D arrays. Also pay attention to compiler warnings. – Lundin Nov 14 '19 at 12:23
  • my compiler just gives me warning "missing braces aroung initializer ",even though the braces are correctly placed.I found out that it is just a bug in gcc.[link](https://stackoverflow.com/questions/13746033/how-to-repair-warning-missing-braces-around-initializer).I am using code blocks ide 16.01 and gcc 8.2.0,do i need to update anything? – alvin lal Nov 16 '19 at 15:16

2 Answers2

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);
}
Blaze
  • 16,736
  • 2
  • 25
  • 44
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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261