Error in structure and string program

I don't know why both of the below program gives error?

int main()
{
typedef union
{
int a;
char b;
float c;
}Un;

Un x,y;
x = {10,'t',5.5};
y.a = 50;
strcpy(y.b,"r");
y.c = 21.50;
printf("Union x: %d %s %f\n",x.a,x.b,x.c);
printf("Union y: %d %s %f\n",y.a,y.b,y.c);
return 0;
}



int main()
{
char *s1 = "Hello";
char *s2 = "World";
char *s3,*s4;
s3 = strcat(s1,s2);
s4 = strncpy(s1,s3,3);
printf("\n %s %s",s3,s4);
return 0;
}
Two main functions? No include files?

Of course, without description of the error, I can only take wild guesses as to what's wrong here.

Please refer to the guidelines for posting queries. Details of the error and your exact code would make it a lot easier to solve. Also, code is a lot more readable if you use the code tags provided.
Here is correct program 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h> // printf

int main(void)
{
    typedef struct // union is not structure!! In union only one item exist at the same time
   {
        int a;
        char b;
        float c;
    }St;

    St x,y;
    x = {10,'t',5.5}; // must be structure
    y.a = 50;
    y.b = 'r'; // "r" is string, but y.b is char
    y.c = 21.50;
    printf("Struct x: %d %c %f\n",x.a,x.b,x.c); // char is not string, you must insert %c instead of %s
    printf("Struct y: %d %c %f\n",y.a,y.b,y.c);
    return 0;
}


Here is correct program 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h> // printf
#include <stdlib.h> // malloc, ...
#include <string.h> // strlen, ...

int main(void)
{
    const char *s1 = "Hello "; // must be const
    const char *s2 = "World"; // must be const
    char *s3; // first possibility
    char s4[100]; // second possibility
    s3 = (char*) malloc((strlen(s1)+strlen(s2)+1) * sizeof(char)); // memory allocation is IMPORTANT
    strncpy(s3, s1); // str 1 copy to str 3
    strcat(s3,s2); // str 2 concat to str 3 (s3 is now "Hello World")
    strncpy(s4, s3, 3);
    s4[3] = 0; // end of string (s4 is now "Hel")
    printf("%s\n%s",s3,s4);
    free((void*) s3); // free memory
    return 0;
}
Last edited on
Topic archived. No new replies allowed.