-4

Printing the initials (first character) of the string held in the variable 'fn' and the variable 'ln'

#include <stdio.h>
#include <cs50.h>

int main(void)
    {
        string fn, ln, initials;

        fn = get_string("\nFirst Name: ");
        ln = get_string("Last Name: ");

        initials = 'fn[0]', 'ln[0]';

        printf("%s", initials)

    }
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
AymenQ
  • 9
  • 1
  • 3

2 Answers2

2

Read more about C. In particular, read some good C programming book, and some C reference site and read the C11 standard n1570. Notice that cs50.h is not a standard C header (and I never encountered it).

The string type does not exist. So your example don't compile and is not valid C code.

An important (and difficult) notion in C is : undefined behavior (UB). I won't explain what is it here, but see this, read much more about UB, and be really afraid of UB.

Even if you (wrongly) add something like

typedef char* string;

(and your cs50.h might do that) you need to understand that:

  • not every pointer is valid, and some pointers may contain an invalid address (such as NULL, or most random addresses; in particular an uninitialized pointer variable often has an invalid pointer). Be aware that in your virtual address space most addresses are invalid. Dereferencing an invalid pointer is UB (often, but not always, giving a segmentation fault).

  • even when a pointer to char is valid, it could point to something which is not a string (e.g. some sequence of bytes which is not NUL terminated). Passing such a pointer (to a non-string data) to string related functions -e.g. strlen or printf with %s is UB.

A string is a sequence of bytes, with additional conventions: at the very least it should be NUL terminated and you generally want it to be a valid string for your system. For example, my Linux is using UTF-8 (in 2017 UTF-8 is used everywhere) so in practice only valid UTF-8 strings can be correctly displayed in my terminals.

Arrays are decayed into pointers (read more to understand what that means, it is tricky). So in several occasions you might declare an array variable (a buffer)

 char buf[50];

then fill it, perhaps using strcpy like

 strcpy(buf, "abc");

or using snprintf like

 int xx = something();
 snprintf(buf, sizeof(buf), "x%d", xx);

and latter you can use as a "string", e.g.

printf("buf is: %s\n", buf);

In some cases (but not always!), you might even do some array accesses like

char c=buf[4];
printf("c is %c\n", c);

or pointer arithmetic like

printf("buf+8 is %s\n", buf+8);

BTW, since stdio is buffered, I recommend ending your printf control format strings with \n or using fflush.

Beware and be very careful about buffer overflows. It is another common cause of UB.

You might want to declare

 char initials[8];

and fill that memory zone to become a proper string:

 initials[0] = fn[0];
 initials[1] = ln[0];
 initials[2] = (char)0;

the last assignment (to initials[2]) is putting the NUL terminating byte and makes that initials buffer a proper string. Then you could output it using printf or fputs

fputs(initials, stdout);

and you'll better output a newline with

putchar('\n');

(or you might just do puts(initials); ....)

Please compile with all warnings and debug info, so gcc -Wall -Wextra -g with GCC. Improve your code to get no warnings. Learn how to use your compiler and your debugger gdb. Use gdb to run your program step by step and query its state. Take time to read the documentation of every standard function that you are using (e.g. strcpy, printf, scanf, fgets) even if at first you don't understand all of it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0
char initials[]={ fn[0], ln[0], '\0'};

This will form the char array and you can print it with

printf("%s", initials) //This is a string - null terminated character array.

There is no concept of string datatype in c . We simulate it using null terminated character array.

If you don't put the \0 in the end, it won't be a null terminated char array and if you want to print it you will have to use indexing in the array to determine the individual characters. (You can't use printf or other standard functions).

int s[]={'h','i'} // not null terminated
//But you can work with this, iterating over the elements.

for(size_t i=0; i< sizeof s; i++)
  printf("%c",s[i]);

To explain further there is no string datatype in C. So what you can do is you simulate it using char [] and that is sufficient for that work.

For example you have to do this to get a string

char fn[MAXLEN}, ln[MAXLEN];

Reading an input can be like :

  if(!fgets(fn, MAXLEN,stdin) ){
    fprintf(stderr,"Error in input");
  }

Do similarly for the second char array.

And then you do form the initializationg of array initials.

 char initials[]={fn[0],ln[0],'\0'}

The benefit of the null terminated char array is that you can pass it to the fucntions which works over char* and get a correct result. Like strcmp() or strcpy().

Also there are lots of ways to get input from stdin and it is better always to check the return type of the standard functions that you use.


Standard don't restrict us that all the char arrays must be null terminated. But if we dont do that way then it's hardly useful in common cases. Like my example above. That array i shown earlier (without the null terminator) can't be passed to strlen() or strcpy() etc.


Also knowingly or unknowingly you have used somnething interesting The comma operator

Suppose you write a statememnt like this

char initialChar = fn[0] , ln[0]; //This is error
char initialChar = (fn[0] , ln[0]); // This is correct and the result will be `ln[0]`

, operator works that first it tries to evaluate the first expression fn[0] and then moves to the second ln[0] and that value is returned as a value of the whole expression that is assigned to initialChar.


You can check these helpful links to get you started

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Alright thank you brother. Putting [] after a variable makes it an array of whatever datatype you declared it ? – AymenQ Nov 25 '17 at 06:48
  • @AymenQ.: It's char array (null terminated) which is basically a string – user2736738 Nov 25 '17 at 06:49
  • :) you da man. lol thx man just startin out im glad this community stuff and ppl like you guys exist – AymenQ Nov 25 '17 at 06:51
  • @AymenQ: when *declaring* a variable, you can use a [] to make an array-type. Examples: `int nums[5];` is an array of 5 integers. The example above omits the number from between the square brackets...this means "determine the size from the number of initializers" ... which is 3 in the example.. – lockcmpxchg8b Nov 25 '17 at 06:53
  • 1
    The last paragraph is BS. `char s[]={ 'a','b'};` is *not* null-terminated. – Antti Haapala -- Слава Україні Nov 25 '17 at 06:54