Thread: string arrays

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    133

    string arrays

    "When a string constant is assigned to a pointer, the C compiler will allocate memory space to hold the string constant,store the starting address of the string in the pointer.It is important to note that the target array must have enough space to hold the string.

    The declaration

    char target[40];

    is used instead of

    char *target;

    It is because the second declaration does not have space allocated to hold the string."

    Let's say a target string constant is assigned to a pointer which is much longer than the string to be copied. Why is it that strncpy() still wont work?

    For example(the following code is compilable),

    [code]

    #include <stdio.h>
    #include <string.h>


    main(void)
    {
    int n;
    char *target = "Target string.(additional space)";
    char *source = "Source string.";

    printf("Input n:");/* n is no of characters to copy */
    scanf("%d", &n);
    printf("Before:\n");
    /* why does the compiler recognise this as an array when it is a pointer?*/
    printf("Target: %s\n",&target[0]);
    printf("Source: ");
    puts(source);
    /* the program doesnt work even though *target have enough space to store source string */
    strncpy(target,source,n);
    if (target[n] != '\0')
    target[n] = '\0';

    printf("After:\n");
    printf("Target: %s\n",target);
    printf("Source: ");
    puts(source);
    return 0;
    }

    [\code]


    This second example uses an array to store the target string and then assign the array to a pointer. This time, the pointer can be passed to the strncpy() and operate the copy function.

    [code]

    #include <stdio.h>
    #include <string.h>



    main(void)
    {
    int n;
    char target[40] = "Target string.";
    char *source = "Source string.";
    /* pointer to point to target[40] */
    char *tar = target;

    printf("Input n:");
    scanf("%d", &n);
    printf("Before:\n");
    printf("Target: %s\n",tar);
    printf("Source: ");
    puts(source);
    /* passing tar to strncpy() */
    strncpy(tar,source,n);
    if (target[n] != '\0')
    target[n] = '\0';

    printf("After:\n");
    printf("Target: %s\n",target);
    printf("Source: ");
    puts(source);
    return 0;
    }


    [\code]

    Sorry for the lengthy post. Hope someone could give me some guidance. Thanks![CODE]
    Code:
    a

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You cannot modify string literals. That's why it doesn't work.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Sep 2003
    Posts
    133
    can you explain more on what is string literals?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    A string literal is a string of characters enclosed in quotation marks. Like so:
    Code:
    char *literal = "You cannot modify this.";
    These are constant and are unmodifiable. It's possible to make 'literal' point to another segment in memory, because you haven't declared the pointer as constant, but in doing so, you lose the literal it points at. (In otherwords, don't do that.)

    If you use arrays, you can modify the contents however:
    Code:
    char modifyable[] = "To an extent...";
    You can modify the contents of this array, however, this array has a fixed size just big enough to hold the string you've given it. This means you can only ever use that many bytes, otherwise a BadThing(TM) will happen.

    The reason string literals are unmodifiable is because they're created at compile time and basicly stored in a string table which you cannot modify.

    Dynamicly allocated memory is a different matter. You can allocate memory, copy strings into it, change them, and free them when you're done. This is because they're not literals.

    The key to remember is that literals are created at compile time, and as such, you cannot modify them.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Sep 2003
    Posts
    133
    Great!...I finally understand on string literals. People like Quzah make this a lovely site.

    As the world of knowledge is limitless, i still have more doubts.

    Code:
    i declared this:
    char *target = "Target string.";
    
    
     /* output is "Target string."  Why does the compiler can recognise this as an array when it is a pointer?*/
    printf("Target: %s\n",&target[0]);

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Arrays of characters which end in a null are strings. You can use the name of the array in almost the same way you can use a pointer.
    Code:
    char foo[] = "This is a string.";
    char *bar = foo;
    
    bar[0] = 'F';
    foo[1] = 'i';
    bar[2] = 's';
    foo[3] = 'h';
    You can do some pointer math on 'foo' and it would work also. Now, the one thing to keep in mind when using array names like you do pointers is that you cannot make them point to something else. Example:
    Code:
    char foo[] = "blah blah";
    char bar[] = "flah flah";
    char *ptr;
    
    ptr = foo; /* valid */
    ptr = bar; /* valid, you can reassign pointers */
    
    bar[0] = foo[0]; /* valid */
    bar = foo; /* not valid */
    
    *(bar+2) = 'a';
    bar += 2; /* not valid because this would chante where 'bar' poitns */
    You can change the value of what is being pointed at, but you cannot change what you're pointing at. That is to say, you cannot just assign 'foo' a new string.

    Arrays always point at the same block of memory. You cannot do anything to change this. You can change what the block holds, but unlike pointers, you cannot make them point elsewhere.

    That is the only real difference as far as C is concerned. (Other than the string literal issue we covered earlier.)

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    You should take a look at assembly if you really want to understand *why* it is so. As quzah said, it is what you must know in C and it will work well with it but it won't tell you why it is so. Just take it as it is or learn assembly.

    And anyway, try to do something like the code below to see what happens.

    Code:
    int **pt;
    int ar[10][10];
    
    pt = ar;
    Indeed, the compiler will emit a warning. It simply means that multi-dimensionnal arrays cannot be used as pointers to pointer and vice versa.

    If you want to know a little more, to the CPU, an array is actually a constant whereas a pointer is a variable.

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >Why does the compiler can recognise this as an array when it is a pointer?

    http://www.eskimo.com/~scs/C-faq/q6.2.html
    http://www.eskimo.com/~scs/C-faq/s6.html
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Registered User
    Join Date
    Sep 2003
    Posts
    133
    Does it means that it takes a longer process to fetch a certain elements in a string using pointers than arrays?

  10. #10
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    Does it means that it takes a longer process to fetch a certain elements in a string using pointers than arrays?
    Actually, yes and not really. It does when you have to load the pointer and it does not really when it is still in a register after some use.

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by Raison
    Does it means that it takes a longer process to fetch a certain elements in a string using pointers than arrays?
    Depending on how you implement it, using a pointer is faster than array subscripting. For example, to access an array like so:
    myarray[i][j] = 1;
    the compiler needs to perform some maths to work out the memory location to store the 1. However, using pointers in the right way, you could have ended up achieving the same result with
    *p = 1;
    Here p is a pointer that gets dereferenced, and the 1 jumps straight in, no maths needed.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #12
    Registered User
    Join Date
    Sep 2003
    Posts
    22

    Arrays and Pointers!!

    Someone would definately have an answer to this very crazy arrays question!!

    Course Prerequisites

    Sample input for this problem might be:
    CS1101 CS1100
    Ma1010 Ma1000
    CS2132 CS1100
    CS3132 CS2132
    CS3132 CS2140
    Each line contains the name of a course and another which is a
    prerequisite for it. There may be any number of lines and in any order.
    The corresponding output would be:
    CS1100 Ma1000 CS2140
    CS1101: CS1100
    Ma1010: Ma1000
    CS2132: CS1100
    CS3132: CS2132 CS2140
    The first line lists those courses which have no prerequisite specified in
    the input data and the remaining lines show the other courses each with
    all the prerequisites it requires.

    Use arrays in C to solve this problem. You may assume that there are
    not more than 50 courses and no course has more than 5 prerequisites.
    One array might contain string pointers - one for each course.
    Use the function strdup(s) which makes a copy of a string and returns a
    pointer to be stored in your array of up to 50 course names.
    Do not use the other memory allocate routines such as malloc.
    Use a 50x5 array of ints where a[i][j] = k indicates that course k is a
    prerequisite for course i.
    M

  13. #13
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>Someone would definately have an answer to this very crazy arrays question!!<<
    If you have a question, ask it. Don't post your homework assignment, no-one's interested in it. Read the forum Guidelines.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  14. #14
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    Depending on how you implement it, using a pointer is faster than array subscripting. For example, to access an array like so:
    myarray[i][j] = 1;
    the compiler needs to perform some maths to work out the memory location to store the 1. However, using pointers in the right way, you could have ended up achieving the same result with
    *p = 1;
    Here p is a pointer that gets dereferenced, and the 1 jumps straight in, no maths needed.
    Well, this is the case of a loop, and, yes, in this case, using pointers is appropriate. However, the use of pointers can be sometimes tricky.

  15. #15
    Registered User
    Join Date
    Sep 2003
    Posts
    133
    Can someone explain how do i intepret this function prototype?

    Code:
    char *strcat(char *s1, const char *s2);
    I know this function appends a copy of the string pointed by s2 to end of string pointed by s1.
    But what does the "*" before the "strcat" mean? What does it serve to place a "*" before a function name. I am only taught to use "*" for pointers.
    Furthermore, what does "const" before char *s2 mean? Am i right to say it means what ever string s2 is pointed to cannot be change. It must remain constant.

    As an aside,
    what is the difference between static and global variables? How do i use them? I believe both can be used in any function once declared and they retain any value assigned to it.
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  5. string handling
    By lessrain in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 07:36 PM