1

I'm a beginner in C and am having some trouble with structures in C. Here is my code;

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

struct rec
{
    char i;
    char b;
    char j;
} ;

int main()
{

 struct rec *p;
 p=(struct rec *) malloc (sizeof(struct rec));
 (*p).i='hello';
 (*p).b='world';
 (*p).j ='there';
 printf("%c %c %c\n",(*p).i,(*p).b,(*p).j);

 free(p);
 getch();
 return 0;
}

The out of this is; o d e

How can I pass in the whole word, rather than just one letter.

2 Answers 2

1

Define the structure members as char *:

struct rec
{
    char *i;
    char *b;
    char *j;
} ;

and use printf with %s:

printf("%s %s %s\n",(*p).i,(*p).b,(*p).j);

Also, you need to replace ' with ": (*p).j ="there"; and if you assign string literals (which may not be modified), change the struct members to const:

struct rec
{
    const char *i;
    const char *b;
    const char *j;
} ;
Sign up to request clarification or add additional context in comments.

2 Comments

The string assignments will also need to be enclosed in double quotes rather than single quotes. Technically the structure members should be declared const char * based on the original code sample.
The original version didn't include it.
0

The common string type in C is char*, which means a pointer to an array of char elements. C marks the end of a string with a special character \0. Those strings are generally called 0-terminated strings.

To save one in your structure you need something like this:

struct foo {
  char* words;
};

Character literals (a.k.a inline strings) have the type const char[n] where n is the length of the string plus one element for the null-terminator, so you cannot assign a character literal to a char*. You will need to allocate strlen(x) + 1 char elements and then copy the contents of the string literal into this memory. Don't forget to free it.

Maybe you should attempt to understand pointers and arrays first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.