Right now I'm trying this:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s %s sourcecode input", argv[0], argv[1]);
}
else {
char source[] = "This is an example.";
int i;
for (i = 0; i < sizeof(source); i++) {
printf("%c", source[i]);
}
}
getchar();
return 0;
}
This does also NOT work:
char *source = "This is an example.";
int i;
for (i = 0; i < strlen(source); i++){
printf("%c", source[i]);
}
I get the error
Unhandled exception at 0x5bf714cf (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation while reading at position 0x00000054.
(loosely translated from german)
So what's wrong with my code?
sizeof(source)
returns the number of bytes required by the pointerchar*
. You should replace it withstrlen(source)
which will be the length of the string you're trying to display.Also, you should probably replace
printf("%s",source[i])
withprintf("%c",source[i])
since you're displaying a character.sizeof(source)
returns sizeof a pointer as source is declared as char *. Correct way to use it isstrlen(source)
.Next:
expects string. i.e %s expects string but you are iterating in a loop to print each character. Hence use %c.
However your way of accessing(iterating) a string using the index i is correct and hence there are no other issues in it.
One common idiom is:
A few notes:
*c++
incrementsc
and returns the dereferenced old value ofc
.printf("%s")
prints a null-terminated string, not a char. This is the cause of your access violation.This should work
Just change sizeof with strlen.
Like this: