Assigning values to arrays

0 santosh gudi · February 18, 2015
My source code is as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char name [3];
    name [0] = "s";
    name [1] = "a";
    printf("My name is %s\n", name);

return 0;
}

And I get the output as below:

My name is

Press ENTER to continue.

Could you please explain where am I going wrong?

Post a Reply

Replies

Oldest  Newest  Rating
0 Danny AA · February 18, 2015
what are you trying to do???
0 Danny AA · February 18, 2015
Are you trying to  print (sa)????
0 Abdullah Nauman · February 18, 2015
If you are trying to print "sa" then why not just do.
#include 
#include

int main()
{

 printf("My name is sa);

return 0;
}
+1 c student · February 18, 2015
you have declared name as an array of chars but you have set the values as strings.  to set them as chars, use single quotes.
0 Dol Lod · February 19, 2015
I would change the array size to 4. Then replace the double quotes for the characters with single quotes. I would make the third byte the null byte now because you are not guaranteed that the last byte is necessarily the null byte. Let me show you what I mean.

char name [4];
name [0] = 's';
name [1] = 'a';
name[2]='\0';
0 Danny AA · February 20, 2015
You need to Initialize the array and put the chars with a single quotes!
0 Mathias Frits Rørvik · February 20, 2015
I would also like to add that you don't need to include stdlib.h, since you're not using any functionality from it.
  • 1

C

107,005 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator