Thursday, January 17, 2008

CSE 2031 Lecture 4

Strings

  • strlen(s)
    • returns length
  • strcmp(s,t)
  • returns positive if s>t, negative if s<t, and 0 if they are equal.
  • strcat(s,t)
    • concatenates t onto s
      • changes string s
    • looks or \o and contatenates at that spot

#include <stdio.h>

Int main(void)

{

char s1[] = {'H','e','l','l','o','\o'};

char s2[4];

printf("Address of s1 is %p\n", s1);

printf("address of s2 is %p\n", s2);

printf("Enter a line: ");

fgets(s2, sizeof(s2), stdin);/* bolded represent extras for using fgets*/

printf("%s\n", s2);

printf("%s\n", s1);

return 0;

}


 

  • Fgets is the new one that works better, if you use just gets you will run into problems with memory over runs
  • Where s1 in this example can be overwritten by s2 if the user input is long enough
  • Look up input and output in textbook
  • With fgets it will only take in the amount of characters assigned after the first comma
  • However if less than the specified amount is passed and the enter key is pushed, the new line character will count as 1 char

Pointers

int n = 5;

int *p;

p = &n

printf("%d\n", *p);

printf("%d\n", n);


 


 

  • *p = 7;
    • Changes whatever value P was addressing to 7

If n = 5, and you said this before printing, it would print 7

No comments: