-2

I am a little confused. I write in pure C. The following code doesn't work:

char arr[] = "0x123";
printf(arr[0]);

It is just an example.

IDE(Code::Blocks) generates this: Program recieved signal SIGSEGV, Sigmentation fault.

Why does this code not work?

Denis
  • 719
  • 2
  • 8
  • 23

3 Answers3

2

If you use llvm/clang, the compiler will issue a rather self-explanatory warning:

test.c:3:9: warning: format string is not a string literal (potentially insecure) [-Wformat-security]
        printf(a[0]);

It means you should provide a formatting string as the first argument e.g. printf("%c", arr[0]);

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
1

Use

printf("%c",arr[0]);

to get the first element of the array

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 1
    This is correct advice but would be better if there was an explanation of why the existing code is wrong and this is right. You might mention `printf("%s\n", arr);` as another option. – Jonathan Leffler Oct 07 '14 at 13:42
1

What you are trying to do does not work because the argument used in the printf function is not correct. printf is called like this:

printf ( const char * format, ... )

As you can see, it needs at least one argument which is a format string and it can take any number of additional arguments as indicated by the ellipsis (...).

The format string may contain any number of format specifiers in the place of which the values of the additional arguments will be printed. Please note that the format specifiers and your additional arguments must match in both number and type.

What you did wrong is that you provided an illegal format string. If you want to print a character from your array your format string must be something that contains the format specifier for a character which is %c. You must also provide the actual value as an additional argument. This means that for the 0-th character in your array the printf should look something like this:

printf("%c", arr[0]);
ravingraven
  • 156
  • 5