1

This is a very quick question. Why am I allowed to do this:

char* sentence[2] ={"blahblah","trololo"};
int main() {
  printf("%s",sentence[0]);
  printf("%s",sentence[1]);
  return 0;
}

but not this?:

 char* sentence[2];
 sentence[0] = "blahblah";
 sentence[1] = "trololo";
 int main() {
  printf("%s",sentence[0]);
  printf("%s",sentence[1]);
  return 0;
}
1
  • Consider if you had multiple source files, each containing code outside of functions. When you compiled it together, when (and in what order) would you expect all of that code to execute? Commented Nov 24, 2013 at 22:03

3 Answers 3

4

You're not allowed to do the second part, because the assignment is outside of a function. When you move the assignment into main() (or another function), it will be valid

char* sentence[2];
int main() {
  sentence[0] = "blahblah";
  sentence[1] = "trololo";
  printf("%s",sentence[0]);
  printf("%s",sentence[1]);
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why am I allowed to do this:

char* sentence[2] ={"blahblah","trololo"};  

Initialization is allowed for global variables.

but not this?:

The statements

sentence[0] = "blahblah";
sentence[1] = "trololo";  

makes no sense outside a function ( main() ). Move them inside the function and it will work.

1 Comment

I am not against downvoting (everytime). I welcome downvotes on my answers if that deserves but I am against the downvoting without any comment. Its really a bad practice.
-3

Sorry i didnt read in a correct way the question and i didnt see the function main()

the code works every time inside the functions. the functions have to be called! main is called by the system. so this code is not attainable.

you can put out from the functions just global variable (example costant) or struct.

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.