NULL reference

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TwOoFtEn
    New Member
    • Apr 2010
    • 2

    #1

    NULL reference

    So I am in school learning how to program... we just did up a little program to count the number of characters in an array. I wrote it so that it would loop, counting as it goes, and end when it hits the NULL thingy....
    It does not however end when it should... and with a printf() I display the contents of each element, and they are just random characters it seems.
    Any help will be appreciated :)

    Code:
    #include "stdafx.h"
    #include <stdio.h>
    
    char first[20];
    char *nameptr;
    
    int counter=0;
    
    int main()
    {
    	
    
    	printf("Enter your first name: ");
    	scanf("%s",first);
    	nameptr=first;
    
    	while(nameptr!=NULL)
    	{
    		nameptr++;
    		counter++;
    		printf("pointer %c\n",nameptr);
    		printf("counter %d\n",counter);
    	}
    	
    	printf("\n%d characters in your name",counter);
    	
    	return 0;
    
    }
    Last edited by Banfa; Apr 16 '10, 09:12 AM. Reason: Added [code]...[/code] tags
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Please use CODE tags when you post source code. If you had then I could refer to line numbers in your source code.

    nameptr points to successive characters within the string. You don't want to stop when the pointer value is NULL; you want to stop when the character being pointed to is null.

    Notice that NULL is different from null!
    • NULL is a value that can be assigned to any pointer. Programs typically use this special pointer value to mean that the pointer variable doesn't point at anything.
    • Null (or null) is a character whose value is '\0'. By definition, all well-formed strings are terminated by null.


    To look at the thing being pointed at by a pointer variable you have to dereference the pointer. This is accomplished by the unary asterisk (*) operator.

    For example, your first printf statement in the loop uses the %c format string (print a single character) on the nameptr variable. You want to print the character being pointed at, not the pointer value itself. For example:
    Code:
    printf("%c", *nameptr);
    Consider a bank with many safety deposit boxes in its vault. Each box has a unique number; and that same number is stamped on the corresponding key. The box number corresponds to a pointer value. The stuff inside the box corresponds to what is being pointed at.

    Comment

    • TwOoFtEn
      New Member
      • Apr 2010
      • 2

      #3
      That was great!
      I learned more in the min that it took to read, than I did in 2 hours of class with my foreign speaking teach.
      Very helpful, thank you!

      Comment

      Working...