1

In C while trying char arrays, I came up with this problem.

void main(){

    char buffer[5] = {'s','d','f','d','f'};
    char a[5] = "sdfdf";
    printf("%d\n", *a==*buffer);
    printf("%s\n", buffer);
    printf("%d\n", (int)strlen(buffer));
    printf("%d\n", (int)strlen(a));
}

Output is

1

sdfdf

sdfdf

5

6
5
  • 1
    So what is the problem? Commented Mar 16, 2015 at 19:41
  • You have undefined behavior. Commented Mar 16, 2015 at 19:43
  • Agreed, it's pure luck that strlen(buffer) did not tell you 42. Commented Mar 16, 2015 at 19:46
  • @WeatherVane or 12. Commented Mar 16, 2015 at 19:46
  • If some tutorial, book, or instructor advised you to use void main(), find get a better one. Use int main(void). (And you omitted #include <stdio.h>.) Commented Mar 16, 2015 at 20:41

1 Answer 1

4

The main problem is the missing '\0', to define a 5 characters string correctly and initialize it from an array of char with an initializer list this is how it should be

char buffer[6] = {'s', 'd', 'f', 'd', 'f', '\0'};

the second variant in your code si wrong because the array can only store 5 characters, so again

char a[6] = "sdfdf";
/*     ^ 6 instead of 5 */

you cannot expect any of the functions following that part of the code to work, when you have a missing '\0'.

All of the printf() with the "%s" spcifier and strlen() expect this last special value '\0' or 0 if you prefer, to be there, when it's not, then these functions invoke undefined behavior because they go beyond the end of the array searching for the '\0'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.