0

I'm trying to learn C for a challenge. I've never been interested in a low-level programming language before. I will now create two different code blocks below as an example. The problem I'm having here is related to array definition and generation. I'm really new to this, if I'm making a mistake, can you guide me in an explanatory way?

Sample1

int main()
{
    char first_name[] = "Joe";
    printf("My name is %s\n", first_name);
}

Sample2

int main()
{
    char first_name[];
    first_name = "Joe";
    printf("My name is %s\n", first_name);
}

Sample3

int main()
{
    char first_name[];
    first_name[] = "Joe";
    printf("My name is %s\n", first_name);
}

Only example1 is running.

I learned that in c we can first create a variable and then use it by defining it. But when I try to do this with arrays, I get an error and the code doesn't work. What is the reason of this? What is the fundamental difference?

  • 1
    What is failing is an assignment, not a definition. You can't assign arrays. You can initialize them when you define them though (which is what your first sample does). – Mat Oct 23 '21 at 07:11
  • I understand better now. C is really hard(different). Sounds very different after JavaScript. I need to change my perspective. In short, I think the answer to this question is as follows. "it doesn't happen because it doesn't happen" –  Oct 23 '21 at 07:15

1 Answers1

0

First point is that you have to know how to declare and initialize array in C programming.

Sample1: In this case you declared and initialized array first_name;

Sample2 and Sample2: You haven't declare and initialize array first_name;

Conclusion: Declaring Arrays Example "type arrayName [ arraySize ];" and Initializing Arrays Example double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; Or balance[4] = 50.0;