-2

My compiler gives me an error when I do this:

strcpy(skin.conclusion[0], "Mel");

My struct looks like this:

struct list{
        char conclusion[10][4] = {};
    }skin;

What am I doing wrong or is there something else other than strcpy that I'm supposed to use.

Jerry Jeremiah
  • 9,045
  • 2
  • 23
  • 32
  • 1
    `char conclusion[10][3] = {};` conclusion is only three characters long. `strcpy(skin.conclusion[0], "Mel");` "Mel" is four characters long (remember the string terminator character...) The compiler can do anything if you invoke undefined behaviour. – Jerry Jeremiah Feb 23 '21 at 20:12
  • Or just C++ `std::string`. – ggorlen Feb 23 '21 at 20:13
  • Oh yeah, thanks, but that still doesn't get strcpy to work. – Miles Banister Feb 23 '21 at 20:13
  • If I copy less characters that it can hold then it works for me: https://onlinegdb.com/xX_szfLeG Make sure you `#include ` – Jerry Jeremiah Feb 23 '21 at 20:13
  • The only error I got was when I said it was a C program and then `char conclusion[10][4] = {};` didn't work because empty braces is a C++ thing. For C you need `char conclusion[10][4] = {0};` You should really put a `C` or `C++` tag on the question so people know how to help you (but not both!) – Jerry Jeremiah Feb 23 '21 at 20:15
  • The link I gave above works for C++. But if you are using C then this works: https://onlinegdb.com/4OkZ3dvDG – Jerry Jeremiah Feb 23 '21 at 20:24

1 Answers1

1

Here is the full code that worked for me. Of course, this is C style C++ and not modern C++, there are many reasons to prefer std::string

#include <iostream>
#include <cstring> 


struct list{
        char conclusion[10][4] = {};
}
skin;
int main()
{
    strcpy(skin.conclusion[0], "Mel");
    std::cout<<skin.conclusion[0];
    return 0;
}
Hisham Hijjawi
  • 1,803
  • 2
  • 17
  • 27
  • To be fair he didn't actually put a C or C++ tag on the question, and since his code didn't compile as C (the empty braces) I assumed he was using a C++ compiler but it is possible he didn't want to be using C++ and wanted to be using C all along. – Jerry Jeremiah Feb 23 '21 at 20:19
  • @JerryJeremiah good point, but since the title explicitly said C++ I thought I'd throw him/her a heads up that in the year 2021 he prbly shouldn't be doing this if he has access to a C++ compiler :) – Hisham Hijjawi Feb 23 '21 at 20:21
  • Sorry - my apologies. I didn't notice that at all. I have added the appropriate language tag. – Jerry Jeremiah Feb 23 '21 at 20:23