views:

55

answers:

2
+2  Q: 

typedef problem

hey people kindly tell me if the following declaration is correct?

if it is then kindly explain

typedef char HELLO[5];

HELLO name;

now what datatype is name? [as in a character,integer etc]

i came to know that name will be an array of strings but when i run the following programme i get error

#include<stdio.h>

typedef char HELLO[5];

void main()
{
    HELLO name;
    name="hey";
    printf("%s",name);
}

error: incompatible types when assigning to type ‘HELLO’ from type ‘char *’

+2  A: 

name is of type char[5] - an array of 5 chars.

Defining name this way

typedef char HELLO[5];

HELLO name;

is equivalent to the definition:

char name[5];

You can't assign a string literal to a char array in C, as in your example. You have to copy the characters from the literal to the array. You can use strncpy() for that.

strncpy(name, "hey", 4); // strlen("hey") == 3. 4 passed to strncpy, as the last
                         // argument causes it to add a null character at the end
Maciej Hehl
+3  A: 

Your problem has nothing to do with typedef. Your type is an array of characters also known as a c style string or a null terminated string for your usage.

You need to use strcpy or even better strncpy to copy a string into a char array. Otherwise you can use the type char* and you can get the address of your string literal stored and then you can print it.

i came to know that name will be an array of strings but when i run the following programme

The correct term would be an array of characters or a buffer. An array of strings might be confused to be an array of array chars.

Brian R. Bondy
yeah...my mistake..
hopefulLLl
thnx...................
hopefulLLl
You don't want to use `strncpy`, it doesn't do what you think it does.
schot