-1

So this structure is per a class assignment, so while there are easier ways to do this, this is the way I am supposed to do it. So structure needs to remain intact. That said, I can not make this print my line.

In Geany it will say it compiled successfully, but when I go to run it in console the char string is 'u????' instead of the string. I'm fairly new to structures in C so I am not really sure what this thing is doing. I have tried using brackets to establish the length of the char array like your supposed to with C, but it would then tell me to remove them. Any help would be greatly appreciated.

#include <stdio.h>

typedef struct {
    unsigned char name;
} MY_DATA;


void name (MY_DATA *n)
{
     n->name = *"Kyle";
}

int main (void)
{
    MY_DATA data;

    name (&data);

    printf ("My name is %s\n", &name);
}
  • 3
    `unsigned char name;` is a single character, not a null-terminated byte string – UnholySheep Aug 01 '21 at 20:06
  • 2
    I suspect you need [a good book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and some time invested in understanding pointers, strings, arrays, etc. The mistakes you're making here have *nothing* to do with specifically with structures per'se. And fyi, sending the address of function `name` to `printf` for a `%s` format specifier should have lit up some huge red warning flags in your compilation. Turn on all warnings and *treat them as errors*, because at this point that is most certainly exactly what they are. – WhozCraig Aug 01 '21 at 20:10
  • `printf ("My name is %s\n", &name);` attempts to take the address of the function `name (MY_DATA *n)` and pass along as the address to a _string_. Kyle Campbell, Why do you want to attempt to print the address of a function? – chux - Reinstate Monica Aug 01 '21 at 20:21
  • 1
    Certainly `typedef struct { unsigned char name; } MY_DATA;` was meant to be `typedef struct { unsigned char *name; } MY_DATA;` (add `*`). – chux - Reinstate Monica Aug 01 '21 at 20:24
  • Thanks but I solved it, typedef var was changed to char *name. main call was changed to data.name = "Kyle". and printf was changed to "%s", data.name. Thanks though for all the help guys. – Kyle Campbell Aug 01 '21 at 20:26
  • The change to `char *name` implies "this is the way I am supposed to do it." lacked verasity. Best not to overstate. – chux - Reinstate Monica Aug 02 '21 at 03:25

1 Answers1

0

I know, that it's already solved, but here is the working code. Also name doesn't need to be unsigned.

#include <stdio.h>

typedef struct {
    char *name;
} MY_DATA;


void name (MY_DATA *n)
{
     n->name = "Kyle";
}

int main (void)
{
    MY_DATA data;

    name (&data);

    printf ("My name is %s\n", data.name);
}
Julian
  • 134
  • 11