0

I guys I have this struct

typedef struct objeto livro;
struct objeto
{
    char titulo[100], autor[100];
    int cota;
};

And this code:

int main()
{
FILE *f;
int tam=5, i=0;
livro c[5];
char a={"a"};

f == fopen("bib.dat", "wb");

if(f == NULL)
{
    printf("erro ao abrir ficheiro");
}

for(i=0; i<tam; i++)
{
    (*c).titulo=a;
    (*c).autor=a;
    (*c).cota=i;
    fwrite(c, sizeof(c), 1,f);
}

return 0;
}

but it says error:assignment to expression with array type on:

(*c).titulo=a;
(*c).autor=a;

I have tried everything I've seen here in the posts my i cant make it work

4
  • 3
    a is a single char. titulo is an array of chars. Therefore the error says you can’t assign them, which is correct. You probably want to use some variant of strncpy() Commented May 29, 2018 at 15:41
  • I think you should learn C language. That's the way the language goes: you cannot assign to an array, full stop. You can assign to pointers, or copy arrays with memcopy, but never try to assign to an array. BTW, char a={"a"}; is a horror: a is a single character while "a" is a string literal that is the const array {'a', '\0'}. Please use char a = 'a'; for a single char or char a[] = "a" for a C string. Commented May 29, 2018 at 15:43
  • The char a={"a"}; is probably giving you a compiler warning, if not an error. If you want a to be an initialized array of characters containing a string, declare it as char a[] = "a";. And as pointed out by Sami Kuhmonen, you cannot use an array as the left side of an assignment. Commented May 29, 2018 at 15:49
  • Did you want c[i] instead of (*c) (which is the same as c[0])? Commented May 29, 2018 at 16:00

2 Answers 2

2

Firstly, char a = {"a"}; is wrong as a is a single char variable but double quotation "a" means thats a string literal. To overcome this error first declare a is a char array like

char a[10] = "a"; 

And then use strcpy() or strncpy(), as (*c).titulo=a won't work because a is now declared as array & assigning one char array to another char array directly like (*c).titulo=a will try to change base address of titulo which is not possible.

Replace below statement

(*c).titulo=a;
(*c).autor=a;

with

strcpy((*c).titulo,a);
strcpy((*c).autor,a);

Secondly, the statement

f == fopen("bib.dat", "wb");

is wrong, probably you want to use = instead of ==

f = fopen("bib.dat", "wb");
Sign up to request clarification or add additional context in comments.

2 Comments

{} means array of characters..you may want to rephrase. say, {1,2,3}
Thanks. I modified @SouravGhosh
0

Use the library function strncpy()for strings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.