Like Tree8Likes

Primary Questions

This is a discussion on Primary Questions within the C Programming forums, part of the General Programming Boards category; lol I read that before, but I'm still confused!!!!!!!!!!...

  1. #16
    Registered User Ashl7's Avatar
    Join Date
    Oct 2012
    Posts
    57
    lol I read that before, but I'm still confused!!!!!!!!!!

  2. #17
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    arrays work like pointers
    When you use just the name of an array as an argument to a function, it will pass in a pointer to the 0th element of the array.

    A c-style string is an array of characters, with the convention of placing a null-character after the end of the string.
    Ashl7 likes this.

  3. #18
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,681
    Quote Originally Posted by Ashl7 View Post
    questions pouring up...
    confirm if this is true:
    char f[3];
    first character goes to slot 0, second goes to slot 1, third to slot 2, forth is a null character which goes to slot 3.(is it true?)
    and null character is what occurs when we're using arrays of characters only(or strings), right?
    If you read the link by Andreas and still confused read this :
    Array indexing in C start from 0 .This is not fortran.
    So if i have this declaration
    Code:
    char array[5];
    then i have 5 elements.
    • the first element in slot (as you say ) array[0]
    • the second element in slot array[1]
    • the third element in slot array[2]
    • the fourth element in slot array[3]
    • the fifth element in slot array[4]

    this all the memory that belongs to you.If you try to access more, then you are cheating and you will receive a segmentation fault or a bus error.

    In C we have to terminate our strings with null terminator.Thus we need space for the null terminator to be saved to.
    Here are seven examples :
    Code:
        /* 1 */ char *s0 = "Lugano";
        /* 2 */ char s1[] = "Bellinzona";
        /* 3 */ char s3[255] = "Locarno";
        /* 4 */ char s4[] = {'M','e','n','d','r','i','s','i','o'};
        /* 5 */ char s5[10] = {'G','i','u','b','i','a','s','c','o'};
        /* 6 */ char s6[] = {'C','h','i','a','s','s','o','\0'};
        /* 7 */ char s7[6] = "Ascona";
    The first one is a string literal.This means that you can not modify its contents but you can set the pointer(s0) to somewhere else.It is terminated by the null terminator automatically.

    /* 2 */
    The compiler will automatically allocate enough space for the string to fit in ,plus one more slot for the null terminator.As a result the size of array s1 will be 10+1 = 11 .Remember that you can modify the contents of this string but you can not set the s1 somewhere else.

    /* 3 */
    The compiler will allocate an array of size 255.In the first 7 slots (slot 0 up to slot 6 ) the contents of the string are going to be saved.In the 7th slot, which the 8th element of your array, a null terminator will be placed by the compiler.Actually because of the brackets, the rest of the unused slots are going to be set at zero.

    /* 4 */
    Now the compiler can not understand that you want to store a string.He only sees characters that are irrelevant for him the one from the other, thus no null terminator will be set after the last 'o'.The size of the array will be 9.This is the length of the string.No null terminator will be added.

    /* 5 */
    The length of the string is 9 characters.So because of the brackets, the compiler will fill the first 9 slots ( slot 0 up to slot 8 ) with the contents of the string, thus the letters , and will put a null terminator after it, because the 9th slot is still unused, so there is space for the nul terminator.This happens because the size of array s5 is equal to 10.If we hadn't specify the size of the array s5 by ourselves, then we would have pretty much the same situation as in case 4.

    /* 6 */
    A well defined string.The size of the array will be equal to 8.Slots 0 up to slot 6 will contain the letters and the 7th slot the null terminator.Notice that nothing is done automatically here, we set the null terminator ourselves.

    /* 7 */
    String "Ascona" has length equal to 6.We have specified the size of array s7 to six.So the letters will be stored successfully, but there is no space for the compiler to go and put the null terminator for us.So , no we will not lose data by getting the last letter replaced by the null terminator.No null terminator will be placed after the string, because there is no space for it.

    But why is everybody so mad about terminating their strings with the null terminator?
    An easy answer is because the functions from the standard libraries of C assume that every single string is terminated properly , which means that after the contents of the string there is a null terminator. Always you should respect this convention.

    Well maybe this example was too much for a beginner.If you did not understand everything, do not worry , practice a little more and come to read the example.

    Take bye bye message :
    • Array indexing starts from zero.
    • Always terminate your strings with the null terminator


    Hope this helps
    Ashl7 likes this.

  4. #19
    Registered User
    Join Date
    Nov 2012
    Location
    Some rock floating in space...
    Posts
    32

    Question

    Quote Originally Posted by Ashl7 View Post
    I guess one reason we use fgets is scanf doesn't read the words after "space"!!!!!!
    Code:
    char buffer[200]; /* safer length for your buffer */
    
    printf("Enter your first and last name: ");
    scanf("%[^\n]",buffer); 
    /* this will read an entire line including spaces between words */
    Not sure if this is glibc specific or not, but it seems to work for reading in an entire line from current position without the trailing new line
    Last edited by twiki; 11-17-2012 at 04:34 PM. Reason: Corrected the code listing with code tags
    Ashl7 likes this.

  5. #20
    Registered User
    Join Date
    Jun 2005
    Posts
    6,311
    Quote Originally Posted by Ashl7 View Post
    questions pouring up...
    char f[3];
    first character goes to slot 0, second goes to slot 1, third to slot 2, forth is a null character which goes to slot 3.(is it true?)
    No it is certainly not true. There is no "slot 3". Any attempt to use "slot 3" (access its value, write to it) causes undefined behaviour. Anything can occur as a result of undefined behaviour, whether it is behaviour that makes sense to you or not. Not crashing is one allowed possibility. Crashing is another allowed possibility. Initiating a current surge through a USB port in order to electrocute the programmer is also an allowed possibility (unfortunately an unlikely possibility, as a system which did that would increase average competence of living C programmers immensely).

    Quote Originally Posted by Ashl7 View Post
    and null character is what occurs when we're using arrays of characters only(or strings), right?
    Wrong.

    In C, by convention, a string is an array of char with the end marked by a character with value zero.

    Defining an array of char ("char f[3];") does not create a string. It creates an array of exactly three characters (which may or may not be initialised, depending on where the definition occurs). It does not create an array of four characters, and certainly does not initialise such a fourth character with value zero.
    Last edited by grumpy; 11-17-2012 at 04:49 PM.
    Ashl7 likes this.
    Right 98% of the time, and don't care about the other 3%.

  6. #21
    Registered User Ashl7's Avatar
    Join Date
    Oct 2012
    Posts
    57
    Thank you aaaalllll... really helped me out here
    STD, the examples were just great!
    Last edited by Ashl7; 11-18-2012 at 01:15 AM.

  7. #22
    Registered User
    Join Date
    Oct 2012
    Posts
    8
    use string functions gets(astring) and puts(astring) to read and write strings including spaces

  8. #23
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,558
    Quote Originally Posted by clearn View Post
    use string functions gets(astring) and puts(astring) to read and write strings including spaces
    I take it you never bothered to read post #10 then.
    NEVER use gets()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #24
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,681
    Quote Originally Posted by Ashl7 View Post
    STD, the examples were just great!
    Glad that they were helpful

  10. #25
    Registered User Ashl7's Avatar
    Join Date
    Oct 2012
    Posts
    57
    I had some question not related to programming this time
    Is it necessary to take C++ before taking Java?! is it going to be hard to understand Java if I don't learn C++ in advance?! which one is harder?! how similar they are?! is learning C++ even needed if I learn Java language?!
    if someone can answer these questions, I just thought not making a new thread because of it and ask all my questions here

  11. #26
    Registered User Ashl7's Avatar
    Join Date
    Oct 2012
    Posts
    57
    Hey all
    can anyone explain to me why this program output is AB?
    I mean I think it should be ABC?! shouldn't it?!
    Code:
    #include <stdio.h>
    
    int main()
    {
        char *ch;
        char vch[]={'A','B','\0','C','\0'};
        ch= vch;
        printf("%s",ch);
        return 0;
    }
    Last edited by Ashl7; 12-15-2012 at 12:51 PM.

  12. #27
    Registered User Ashl7's Avatar
    Join Date
    Oct 2012
    Posts
    57
    and why does this one prints out AB?! it should be A itself, since the character in slot 0 is A!!!
    Code:
    #include <stdio.h>
    
    int main()
    {
        char *ch;
        char vch[]={'A','B','\0','C','\0'};
        ch= &vch[0];
        printf("%s",ch);
        return 0;
    }

  13. #28
    Registered User
    Join Date
    Nov 2012
    Posts
    1,101
    Think of a pointer as an arrow which points to somewhere in memory. In this case the spot in memory called vch is 5 characters

    'A' 'B' '\0' 'C' '\0'

    The expression vch[0] refers to the single character in slot 0, represented as 'A'.
    The expression &vch[0] constructs a pointer to this character, which might be represented by drawing an arrow to the character in a diagram:

    ->'A' 'B' '\0' 'C' '\0'

    Printing a string is defined very simply: print the character that the arrow points to, advance the arrow, print that character, advance the arrow, and so on. Keep doing this until the arrow points to a '\0' character.

    This is the answer to both of your previous questions. Now you should be able to answer the output of:
    Code:
    vch[2]='x';
    printf("%s", &vch[1]);

  14. #29
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,305
    printf takes a pointer and prints out every character on from there until it encounters a nul character.
    You are giving it a pointer to the same string in both cases where the the third character it sees is a nul. So of course they behave the same.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  15. #30
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Ashl7 View Post
    questions pouring up...
    confirm if this is true:
    char f[3];
    first character goes to slot 0, second goes to slot 1, third to slot 2, forth is a null character which goes to slot 3.(is it true?)
    and null character is what occurs when we're using arrays of characters only(or strings), right?
    This is a string - but the last char you will never see:
    Four score and seven years ago\0

    This is just a bunch of chars - but NOT a string:
    Four score and seven years ago

    Without the NULL char on the end, there is no string, in C.

    This is a way to use scanf() to bring in first and last names, with just a space between them, on the same line of text. Each struct member is separated by a comma.

    Code:
    /* The names.txt file is:
    Abe Alfa,10,Male
    Bella Bravo,15,Female
    Charles Charlie,18,Male
    Donna Delta,22,Female
    */
    
    /*
    #include <stdio.h>
    
    typedef struct {      //declare a structure
       char fname[30];    //for each student record
       char lname[30];
       int age;
       char sex[6];
    }students;            
    
    int main(void) {
       FILE *fpIn;
       int i,studnumber;
       char buffer[80];
       students stud[4];   //make an array of student records
    
       fpIn=fopen("names.txt","r");
       if(!fpIn) {
          printf("Error opening file!\n");
          return 1;
       }
       i=0;
       while(fgets(buffer, sizeof(buffer), fpIn)) { 
          sscanf(buffer, "%s %[^,],%d,%s",stud[i].fname,stud[i].lname,&stud[i].age,stud[i].sex);
          printf("Name: %s %s \nAge: %d \nSex: %s\n",stud[i].fname,stud[i].lname,stud[i].age,stud[i].sex);
          ++i;
       }
       studnumber=i;
    
       fclose(fpIn);
       printf("\nnumber of students: %d \n",studnumber);
       return 0;
    }
    There is a field length format specifier for scanf(), but it's for strictly formatted data only. It simply cuts off any further data entry - BOOM!

    Probably that's not what you want.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. primary-expression error
    By sopa in forum C++ Programming
    Replies: 1
    Last Post: 07-20-2012, 10:20 AM
  2. primary expression before else
    By Rareit in forum C++ Programming
    Replies: 4
    Last Post: 12-03-2010, 10:12 PM
  3. Epected Primary Errors
    By veronicak5678 in forum C++ Programming
    Replies: 7
    Last Post: 09-29-2007, 02:12 PM
  4. expected primary expression
    By mju4t in forum C Programming
    Replies: 2
    Last Post: 03-27-2007, 06:59 PM
  5. Primary colors question
    By Robin Hood in forum C++ Programming
    Replies: 8
    Last Post: 07-25-2002, 04:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21