Andriy Veres
Andriy Veres

Reputation: 81

Char string in a struct C

I need your help! Why in C structures of data that stores in char strings works only 1 type of declaration: char *name; works, but char []name; does not work.

But when to try declare a char string inside the code (without using struct), everything works. Code example that illustrate, what when to declare char array, both of the declaration types works.

#include "funct.h"
#include "stdio.h"

//structure employee name and surname only works when using char* pointers

struct employee {
    char *name;
    char *surname;
};

int main() {
    struct employee worker;
    worker.name = "Robert";
    worker.surname = "Woz";

    printf("\n");
    printf("%s", worker.name);
    printf("\n");
    printf("%s", worker.surname);
    printf("\n");

    char name[] = "Robert";   //declaration of array with using [] postfix

    for (int i = 0; i < 7; i++) {
        printf("%c", name[i]);
    }

    printf("\n");

    char *surname = "Woz";   //declaration of array wit using char* pointer

    for (int i = 0; i < 4; i++) {
        printf("%c", surname[i]);
    }

    printf("\n");

    return (0);
}

Program output:

Robert
Woz
Robert
Woz

Upvotes: 1

Views: 14460

Answers (3)

user7122338
user7122338

Reputation:

According to your question.

  1. Header file quotes. < > instead of " "
  2. I don't think that , C allows the Array declaring like Java do. char name[] = " "; instead of char []name=" ";

    *name is simply a pointer.

Upvotes: 0

bzim
bzim

Reputation: 1070

First of all, to include the standard library headers use <header.h> instead of "header.h". When using the quotes the compiler will atempt to find the header in the file directory. When using <> the compiler looks for the header in your include directory.

Secondly, the declaration using brackets accepts only char name[];, not char []name;. But if you declare this way in a structure, you need to specify the size, like char name[30];. You can only declare without a size when declaring a single variable and initializing it with a string literal, so the compiler will deduce the size from the string literal. Example: char name[] = "Robert";.

Thirdly, the difference of declaring char* name from declaring char name[30] is that in the first way you declare a pointer to a sequence of chars in the memory, while in the second way, you declare a fixed size array. Note that assigning a fixed size array to a smaller string literal (or bigger) after its initializing may result in an error, while assigning a char pointer will allow you assinging it to any size string literal.

Upvotes: 3

Dot31
Dot31

Reputation: 11

If you use char name[] in a struct, your compiler don't know the size of the char tab. That's why you have to use a pointer in your struct type, or you could use

char name[MAX_SIZE]; in your struct type.

But I recommand using pointers :)

Upvotes: 1

Related Questions