Hey, i'm new here and hoping to get a few noobish questions answered

This is a discussion on Hey, i'm new here and hoping to get a few noobish questions answered within the C Programming forums, part of the General Programming Boards category; Hi everyone. Basically i want to be good at c programming. But everytime i start to get into it. I ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    79

    Hey, i'm new here and hoping to get a few noobish questions answered

    Hi everyone. Basically i want to be good at c programming. But everytime i start to get into it. I get frustrated that i cant do something i want to do and end up leaving it. Hopefully with your help i can get these questions answered.

    So just for a start ive got a few random questions.

    1) if you have a struct with a variable like char *name; in it. Can you assign it a value by doing structname->name = "myname"; or is that wrong? Do you have to malloc it some space first?

    2) Some source code i look at keeps talking about HANDLE - what is this and what is it used for?

    3) How can you use strtok to split a string into an array? ive seen different example but i cant understand most of them.

    A program im trying to make at the minute is a gym program. Which uses a weight lifting routine of 3 exercises

    bench press, squat and power clean.

    I wanted the program when it was first run to detect the date and store it somewhere permanent that it could access when its run again.

    I was looking it to realise when it was run a second time, that it had run before and compare the date now, to the date when it was first run. Then count how many weeks the program had started and add the right amount of weights to the lift

    so to summerise.

    Make the program know its been run before.
    Make it be able to calculate how many weeks since it was first run - using difftime().

    Also wanted to store the previous lifts in a file. But ive not idea how to effectively pick correct data from a file. i.e how to find the number and how to save it as an int.

    sorry if this is too many questions or unclear. But these things have been bugging me and i really want to understand it all.

    Thanks.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by mushy View Post
    Hi everyone. Basically i want to be good at c programming. But everytime i start to get into it. I get frustrated that i cant do something i want to do and end up leaving it. Hopefully with your help i can get these questions answered.

    So just for a start ive got a few random questions.

    1) if you have a struct with a variable like char *name; in it. Can you assign it a value by doing structname->name = "myname"; or is that wrong? Do you have to malloc it some space first?
    Depends on what you want to achieve. Essentially, you have to choose EITHER assign it with a constant, or malloc memory (and use strcpy() to fill it in).

    2) Some source code i look at keeps talking about HANDLE - what is this and what is it used for?
    The term handle is used frequently in computer systems - it is a generic term for "something that can be used to access a resource without the user function needing to know what it represents". In general, it is an integer type that you get back from the OS or some runtime functions when you open or create something (a graphical window, file or such), and can be passed back to the OS/runtime functions when you want to use that something (e.g. draw some pixels in the window or read/write a file).

    3) How can you use strtok to split a string into an array? ive seen different example but i cant understand most of them.
    This is a bit more complex to just answer - if you post an example of something that you want explained, I'm sure someone can explain it.

    A program im trying to make at the minute is a gym program. Which uses a weight lifting routine of 3 exercises

    bench press, squat and power clean.

    I wanted the program when it was first run to detect the date and store it somewhere permanent that it could access when its run again.

    I was looking it to realise when it was run a second time, that it had run before and compare the date now, to the date when it was first run. Then count how many weeks the program had started and add the right amount of weights to the lift

    so to summerise.

    Make the program know its been run before.
    Make it be able to calculate how many weeks since it was first run - using difftime().

    Also wanted to store the previous lifts in a file. But ive not idea how to effectively pick correct data from a file. i.e how to find the number and how to save it as an int.

    sorry if this is too many questions or unclear. But these things have been bugging me and i really want to understand it all.

    Thanks.
    All of your above ideas seem quite doable.

    Since your data format is entirely up to you, it is just a normal "read data from a file and make it into a number". There are many different ways, but one of those is to use fgets() to fetch a line of data, and then use for example sscanf() and/or strtok() to get the data out of the string. This is better than using fscanf(), as if there's something wrong with the input, fscanf() can easily be confused in such a way that you don't get anything useful out of it ever again [until you stop the program and start it over again, that is - it's not a "permanent forever failure"].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    Quote Originally Posted by mushy View Post
    1) if you have a struct with a variable like char *name; in it. Can you assign it a value by doing structname->name = "myname"; or is that wrong? Do you have to malloc it some space first?
    Now, while it certainly works, I don't know if I would recommend it for char*.
    It's best to allocate using malloc and strcpy the string into there.
    If it was const char*, however, then it should be perfectly fine to assign it as you mention.

    Make the program know its been run before.
    Make it be able to calculate how many weeks since it was first run - using difftime().
    To do such a thing, one way would be to open a file, if it doesn't exist, it's the first time the program is run, so open the file and write the date, then close.
    All other times the program is run, it will successfully open the file and read that date. So then you can compare the dates and output accordingly.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    Hey matsp. Thanks for the info.

    Regarding strtok. i was looking to use it in this way.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    typedef struct{
                  char *word;
    }s;
    
    int main(){
            int wordcount;
            char str[] = "This is a string to split";
            for(int i = 0; i < strlen(str); i++)
                 {
                       if(str[i] == ' ')
                         {
                              wordcount++; //find out how many words there are.
                         }
                 }
                  wordcount +=1; // add one to account for the last word
           s splitter[wordcount]; // create a struct for every word in string

    This is where im stuck, how can i assign each word in the string to the variable splitter[0]->word in each of the array?

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    Hey elysia.

    can you explain why its different for a const char* and an ordinary char *?

    Also i reading in the cplusplus c reference library about the time.h header file. But there dosent seem to be a function that just gives you the current date and time?

    also why do you need to use size-t and time_t sometimes as opposed it an int?

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Ok, using variables to create array is not allowed in standard C, so perhaps you may want to rethink that one.

    Also, aside from the fact that you would have to know from the beginning how many words you have, you don't actually benefit from using strtok() if you are already walking through the string itself.

    Something like this would do:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAXWORDS 100    // Something large enough
    
    typedef struct{
                  char *word;
    }s;
    
    int main(){
            s splitter[MAXWORDS]
            int wordcountn = 0;
            int len;
            char str[] = "This is a string to split";
            char *pword = str;
            len = strlen(str);
            
            for(int i = 0; i < len; i++)
                 {
                       if(str[i] == ' ')
                         {
                              splitter[wordcount].word = pword;
                              str[i] = 0;
                              p = &str[i+1];
                              wordcount++; //find out how many words there are.
                         }
                 }
                  wordcount +=1; // add one to account for the last word
    You'll have to fix up the last word yourself.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    Quote Originally Posted by mushy View Post
    can you explain why its different for a const char* and an ordinary char *?
    Char* is a pointer to char. An array of chars, typically.
    Const char* is a pointer to const char. So an array of const chars, typically. Since it's const, the contents of the value or array pointed to cannot change.
    A string literal, such as "MY string" is a const char*, because you cannot change the contents of that string. Therefore, it should be assigned to const char*.
    Assigning it to char* should be a mistake since if you try to modify the contents later, you'll get a seg fault. So you should declare it as const char* from the beginning. That way, you can't accidentally assign or change something later.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    Hey matsp i was doing it this way because i assumed it was the only way?

    Also i dont have a clue how this works?

    Code:
    if(str[i] == ' ')
                         {
                              splitter[wordcount].word = pword;
                              str[i] = 0;
                              p = &str[i+1];

  9. #9
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    ok thanks Elysia. So what if you tried to assign char *name a value from an inputed variable? is it ok then?

  10. #10
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    matsp just to elaborate further on why i dont get this

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAXWORDS 100    // Something large enough
    
    typedef struct{
                  char *word;
    }s;
    
    int main(){
            s splitter[MAXWORDS]
            int wordcountn = 0;
            int len;
            char str[] = "This is a string to split";
            char *pword = str;
            len = strlen(str);
            
            for(int i = 0; i < len; i++)
                 {
                       if(str[i] == ' ')
                         {
                              splitter[wordcount].word = pword; // assigning the value pword to the word variable - earlier you assigned pword to the value of the whole string - so the whole string is stored in splitter[0].word?
                              str[i] = 0; // putting i back to the start of the string
                              p = &str[i+1]; // dont know how this splits it
                              wordcount++; //find out how many words there are.
                         }
                 }
                  wordcount +=1; // add one to account for the last word

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    OK, what you must understand is that strings are just an array of chars, and at the end, there's an extra char with the value '\0' (or 0).
    So when function read the '\0', they know they're found the end of the string.
    So what mats is doing is truncating the string but replacing the ' ' with '\0', so it really marks the end of the string. Or so functions will believe.
    Then just set a new pointer to begin pointing at the character after the '\0'.
    The string will look like:
    "This\0is\0a\0string\0to\0split"
    And the word member of the struct will point at:
    "This\0is\0a\0string\0to\0split" -> Essentially "This"
    "is\0a\0string\0to\0split" -> Essentially "is"
    "a\0string\0to\0split" -> Essentially "a"
    "string\0to\0split" -> Essentially "string"
    "to\0split" -> Essentially "to"
    "split"

    As for the char* question... if you have a char* pointer, then it's best to allocate memory and use strcpy to copy the string in there. Thus, you can modify the string if you want.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    ok i think i understand elysia. So basically.

    p = &str[i+1]; // was the p ment to be pword? i can see that this points to the space next char after the space!

    I still dont understand two things though.

    Why does the full string not get assined to splitter[wordcount].word ? why does it stop reading when it gets to the first space. i mean if you done

    char s1[] = "this is a string";
    char s2[100] = s1;

    unless im wrong it wouldnt just copy the first word across! also it wouldnt leave s1 equaling "is a string" with the first word missing

    i realise this is wrong. Because obviously the code matsp posted will work, but im just trying to find out how it works. Sorry for being an idiot.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    Quote Originally Posted by mushy;711867 p = &str[i+1
    ; // was the p ment to be pword? i can see that this points to the space next char after the space!
    I assume so, yes.

    Why does the full string not get assined to splitter[wordcount].word ? why does it stop reading when it gets to the first space.
    Because mats's code replace the space with a '\0', basically marking the end of the string.

    i mean if you done

    char s1[] = "this is a string";
    char s2[100] = s1;

    unless im wrong it wouldnt just copy the first word across! also it wouldnt leave s1 equaling "is a string" with the first word missing
    I'm pretty sure that won't compile at all. Anyway, the point is that we're working with pointers, not the full data itself.
    The data is stored somewhere in memory and all we do is pass around the address of where the string begins. The '\0' char marks the end of the string.
    So if you just pass around a pointer without modifying it, all pointers will show the same data. And if you modify the data itself, all pointers will change.
    In your sample, you're trying to copy the data from one char array to another, I'm guessing. This should be done via strcpy. But we're not modifying the data itself, as I explained. We're passing around pointers.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    ok. i think i understand now. Were not actually doing anything to the original string. Were just using pointers to pick from different points of the string.


    str[i] = 0; -- i get what this does now, it replaces spaces with 0. I thought originally that it was trying to go back to the first character of the string.

    I get it now. Thanks for the help. Now that i know this it sould make reading and editing the data in the file easier.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    Quote Originally Posted by mushy View Post
    ok. i think i understand now. Were not actually doing anything to the original string. Were just using pointers to pick from different points of the string.
    Although you could say we're modifying the data by replacing the spaces, but other than that, we're not modifying it anything.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

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