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?
You want:
sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:
but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:
or rewrite the loop:
sizeof(source)
is returning to you the size of achar*
, not the length of the string. You should be usingstrlen(source)
, and you should move that out of the loop, or else you'll be recalculating the size of the string every loop.%s
format modifier,printf
is looking for achar*
, but you're actually passing achar
. You should use the%c
modifier.Rather than use strlen as suggested above, you can just check for the NULL character:
Replace sizeof with strlen and it should work.
You need a pointer to the first char to have an ANSI string.
will do the job
Plus, of course you should have meant
strlen(source)
, notsizeof(source)
.