0

I'm writing a code that bring the values from a structure called "data", captures it in the main() function and then use the value inside "my_friend.friend_age" as a parameter in the function sum() to sum 20 to the value inside "my_friend.friend_age" and, afterward, return the value and show it to the user. `

#include <stdio.h>
int sum(struct data age);

struct data{
    char name_friend[50];
    int friend_age;
};

struct data my_friend; 

int main(){
    int d;
    printf("Type your friends name: ");
    scanf("%s", &my_friend.name_friend);
    printf("Type your friends age: ");
    scanf("%d", &my_friend.friend_age);
    d= sum(my_friend.friend_age);
    printf("%d", d);
}

int sum(struct my_friend age)
{
    int agein_20;
    agein_20= agein_20 + age;
    return agein_20;
}

` However, at the time of compile it and run it I'm getting errors such as: enter image description here I'd really appreciate your help because I'm not sure about what I'm doing wrong ;)

  • 1
    `struct my_friend` is not `struct data` – Cheatah Nov 01 '22 at 03:04
  • 2
    Change `int sum(struct my_friend age)` to `int sum(int age)` – rslemos Nov 01 '22 at 03:04
  • Never use `%s` as a specifier for `scanf`, it does not limit how many bytes are stored and thus is guaranteed to be vulnerable to a buffer overflow. Always make sure you limit the input to a specific size. – Cheatah Nov 01 '22 at 03:06
  • Just to point out. the variable `int agein_20` is undefined behavior since its value is not initialized – jvx8ss Nov 01 '22 at 03:16
  • `scanf("%s", &my_friend.name_friend);` is wrong, because `&my_friend.name_friend` is not a `char *`. It should be either `scanf( "%s", &my_friend.name_friend[0] );` or `scanf( "%s", my_friend.name_friend );`. Both are equivalent, due to [array to pointer decay](https://stackoverflow.com/q/1461432/12149471). – Andreas Wenzel Nov 01 '22 at 03:17
  • Thank u, I could fix it <3 – Diego Albarracin Nov 01 '22 at 03:22

1 Answers1

0

Here are the changes I made:

  1. Changed struct data to eliminate friend part in each variable.
  2. Made my_friend a local variable instead of a global variable.
  3. Specified field width when reading name using a bit of macro magic to convert a number to a string.
  4. In first scanf() the variable type was incorrect. It should just be my_friend.name.
  5. Eliminated the d variable.
  6. Moved sum() before main() to get away with not using a separate prototype.
#include <stdio.h>

#define str(s) str2(s)
#define str2(s) #s

#define NAME_LEN 49
struct data {
    char name[NAME_LEN];
    int age;
};

int sum(int age) {
    return age + 20;
}

int main(void) {
    struct data my_friend;
    printf("Type your friends name: ");
    scanf("%" str(NAME_LEN) "s", my_friend.name);
    printf("Type your friends age: ");
    scanf("%d", &my_friend.age);
    printf("%d\n", sum(my_friend.age));
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38