Friday 15 February 2013

Char array pointer in C -


I want to run this code but I can not I have just started learning pointer in C I am trying to get addresses of letters. The problem is printf ("adress:% p \ n", p [i]) ; 'Thank you'

  #include & lt; Stdio.h & gt; Int main (zero) {letter four; Int c = 0; Int i; Four patterns [7]; Four * p; Printf ("Enter a letter:"); Scanf ("% c", & amp; letter); Printf ("Enter a pattern:"); Scanf ("% s", pattern); P = pattern; For {I = 0; i <7; i ++} {if (letter == pattern [i]) {c ++; Printf ("Letter found in lt;% c & gt; pattern% s \ n", letter, pattern); Printf ("adress:% p \ n", p [i]); Printf ("index:% d \ n", i); }} If (c == 0) printf ("no letter in pattern is included"); Return 0; } This line of code has some potential problem which can be easily < / P> 
  scanf ("% s", & amp; pattern);  

You can make it a little safer like this

  scanf ("% 6s", & pattern);  

This is a 6 because you need an extra byte '\ 0' at the end of the string, which gives us

Here you are assuming that all the bytes are non- null / code> which will be fine except that you scanf () and you do not make a byte larger than the number of characters that you want to store it, you should fill it with the scanf () array that means it is byte Beyond Write a byte.

It is resolved by adding the "% 6s" length specification to the format string, but you can solve 6 non- null in the array < / Code> Store bytes, and other problem

 for  (i = 0; pattern [i]! = '\ 0'; i ++)  

Better, because you do not need to know the length of the string in advance and at the end of the end you do not have the risk of reading the array.

Try this:

  #include & lt; Stdio.h & gt; Int main (zero) {letter four; Four c; Int i; Four patterns [7]; Printf ("Enter a letter:"); If (scanf ("% c", and characters)! = 1) {printf ("Error: invalid input. \"); Return -1; } Printf ("Enter a pattern:"); If (fgets (Pattern, Size (pattern), stdin) == NULL {printf ("Error: End of file. \"); Return -1; } For (i = 0; pattern [i]! = 0; ++ i) {if (letter == pattern [i]) {c ++; Printf ("Letter found in lt;% c & gt; pattern% s \ n", letter, pattern); Printf ("adress:% p \ n", pattern + i); Printf ("index:% d \ n", i); }} If (c == 0) printf ("no letter in pattern is included"); Return 0; }  

You had even printed the wrong address, because in the indicator [i] , the redirects the subscript operator indicator, it is * (poitner + I) .


No comments:

Post a Comment