0

Please tell me why strcpy fails. Im trying to copy the value str1 into one of the element of str2.

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

int main(int argc, char *argv[]) {

    char str1[]={"cat"}; //string
    char *str2[]={"mouse","dog"}; //array
    strcpy(str2[0],str1);       

    return 0;
}   
Unheilig
  • 16,196
  • 193
  • 68
  • 98

1 Answers1

1
char str1[]={"cat"}; //string

is wrong in this context

"" is a replacement for tedious {'a','b'...'\0'}.

Do either

char str1[]="cat";

or

char str1[]={'c','a','t','\0'};

Even then your code wouldn't work

strcpy(str2[0],str1); 

because you are trying to write into a read-only hard coded memory

as [ @michi ] mentioned in his comment.

But below would work

str2[0]=malloc(sizeof(str1)); // You allocate memory for str2[0];
strcpy(str2[0],str1); 
printf("str2[0] : %s\n",str2[0])

Also remember to free the allocated memory after use

free(str2[0]);
Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 2
    This helps the OPs problem? – Michi Jul 14 '16 at 03:37
  • @Michi : Updated. Guess the op need to be good with the terminology and sure they need a good book – sjsam Jul 14 '16 at 03:39
  • 1
    thank you. Changing the declaration to str2[2][20] makes it editable. I'm just wondering how to make str2 as parameter of a function and reference each element by index; – Gerie Tanabe Jul 14 '16 at 04:04