Thread: How to printf NULL

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    85

    How to printf NULL

    Hello, i have made an array of pointers and i have filled the array with NULL values in every index

    When i'm trying to print the value of each cell/index i do:

    printf("%s\n",array[i]); and i get Segmentation fault

    but when i do printf("%d\n",array[i]); i get 0 for every value and the program runs

    Do you know how i can printf the word NULL for every index?

    Thanks in advance!

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Try this:
    Code:
    printf("%s\n", ( array[i] ? array[i] : "NULL") );
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Dec 2006
    Posts
    85

    Smile

    Hi, thanks for replying!

    It works and i get a warning: pointer type mismatch in conditional expression but it's ok cause the program runs now!!!

    Do you know what i shall do in order not to have this warning?

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    What is the type of array?

  5. #5
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Post more of your code and note the exact error.
    Mainframe assembler programmer by trade. C coder when I can.

  6. #6
    Registered User
    Join Date
    Oct 2006
    Posts
    250
    printf("%s\n", string), will try to print the contents of the zero terminated array at the location pointed to by string, i.e. it tries to dereference the pointer stored in array[i].
    printf("%d\n", string), will try to print the decimal representation of the location of that array, i.e. the value of the pointer you stored in array[i].

    If you want to use the first statement, you must make sure that the pointer is not zero. You could do this by storing a pointer to an empty string, which is just a *pointer* to the value zero. This way, the pointer gets dereferenced correctly and your program doesn't segfault, while still displaying an empty string.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  2. Compiling 3rd party code problem me too
    By siavoshkc in forum C Programming
    Replies: 1
    Last Post: 09-12-2007, 05:55 AM
  3. Syntax Error??
    By Kennedy in forum C Programming
    Replies: 8
    Last Post: 09-06-2006, 11:04 AM
  4. linked list problem
    By kzar in forum C Programming
    Replies: 8
    Last Post: 02-05-2005, 04:16 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM