0

I read somewhere that i should be able to initialize the array like that. but why isn't it working.

#include<stdio.h>

main()
{
   char s[10];
   s[10]="pen";
   printf("%s\n",s[10]);    
}

output: NULL

1
  • Save time, enable all compiler warnings. Commented May 29, 2020 at 13:09

4 Answers 4

2

This is initialization: char s[10] = "pen";
This is assignment (and invalid syntax): s[10]="pen";

Similar syntax but different terms. Initialization is done together with the variable declaration. Generally, initialization could be carried out before the program is launched. Had you for example written const char s[10] = "pen";, then the string could be pre-loaded into the variable before the program starts.

Since s[10]="pen"; is invalid C but your compiler let it through with a warning (which you probably didn't read), consider compiling with stricter compiler settings. On gcc this means compiling with -pedantic-errors -Werror, which I strongly recommend beginners to use.

Sign up to request clarification or add additional context in comments.

Comments

2

Strictly speaking this statement

s[10]="pen";

is not an initialization. It is an assignment. You are trying to assign the string literal "pen" having the type char * to a non-existent element of the type char of the array s with the index 10.

So the both these statements

s[10]="pen";
printf("%s\n",s[10]);

invoke undefined behavior.

Pay attention to that arrays have no the assignment operator. Arrays are non-modifiable lvalues. If you will write for example

s = "pen";

the compiler will issue an error.

What you need is the following

char s[10] = "pen";
printf("%s\n",s); 

That is in this case the array s will be initialized with elements of the string literal. All elements that do not have a corresponding initializer of the string literal will be zero-initialized.

If to use assignments instead of the initialization then this declaration

char s[10] = "pen";

is equivalent to

char s[10];
s[0] = 'p';
s[1] = 'e';
s[2] = 'n';
s[3] = '\0';
s[4] = '\0';
s[5] = '\0';
s[6] = '\0';`
s[7] = '\0';
s[8] = '\0';
s[9] = '\0';

`

Comments

1

After the array is declared, it is no longer an "initialization".

You are attempting an assignment.
But you cannot assign an entire array using the syntax: s[10]="pen";

main()
{
   char s[10] = "pen";    // Initialization
   printf("%s\n",s);    
}

Comments

0

Here is the solution to your problem

#include<stdio.h>

main()
{
   char s[10] = "pen";
   printf("%s\n",s);    
}

And you can't access s[10] as indexing start from 0 i.e s[0]-s[9] Reason for NULL output is len(s) is 3

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.