Ad

Is There A Quick Way To Get The Last Element That Was Put In An Array?

- 1 answer

I use an fgets to read from stdin a line and save it in a char array, I would like to get the last letter of the line i wrote , which should be in the array before \nand \0.

For example if i have a char line[10] and write on the terminal 1stLine, is there a fast way to get the letter e rather than just cycling to it?

I saw this post How do I print the last element of an array in c but I think it doesn't work for me, even if I just create the array without filling it with fgets , sizeof line is already 10 because the array already has something in it

I know it's not java and I can't just .giveMeLastItem(), but I wonder if there is a smarter way than to cycle until the char before the \n to get the last letter I wrote

code is something like

char command[6];
fgets(command,6,stdin);
Ad

Answer

If you know the sentinel value, ex: \0 (or \n ,or any value for that matter), and you want the value of the element immediately preceding to that, you can

  • use strchr() to find out the position of the sentinel and
  • get the address of retPtr-1 and dereference to get the value you want.
Ad
source: stackoverflow.com
Ad