0

May someone explain me what the '8' of the buffer variable means? I know here involves arrays but I am not clear what is implied if the number is for example changed to 30.

#include <stdio.h>

int main (void)
{
    char buffer[8];

    int course = 50;

    sprintf(buffer,"CS%d rocks!", course);

    printf("%s\n", buffer);
}
1

When you declare the char array, as char buffer[8], you are creating an array that holds 8 characters. (This should generally be large enough to include the \0 end of string character, but that's another discussion.) You can't change the size of the array once created.

Once declared, you can access any element in that array, using the index of the array. For instance, if you had an array x[] with 10 elements (0 through 9), you could access the 5th element with x[4]. Here is a small program to play with.

#include <stdio.h>

int main()
{
    char x[10] = "abcdefghi";
    for(int i=0; i<10;i++) printf("x[%i]=%c.\n",i,x[i]);
    printf("%s\n",x);
}

Obviously, you can't use an index larger than the number of elements -1.

For more details, review the class material or google "char arrays in c"

If this answers your question, please accept the answer to remove your question from the unanswered question pool. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .