Right now I\'m trying this:
#include
int main(int argc, char *argv[]) {
if (argc != 3) {
printf(\"Usage: %s %s sourcecode inpu
Just change sizeof with strlen.
Like this:
char *source = "This is an example.";
int i;
for (i = 0; i < strlen(source); i++){
printf("%c", source[i]);
}
One common idiom is:
char* c = source;
while (*c) putchar(*c++);
A few notes:
*c++
increments c
and returns the dereferenced old value of c
.printf("%s")
prints a null-terminated string, not a char. This is the cause of your access violation.This should work
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char *source = "This is an example.";
int length = (int)strlen(source); //sizeof(source)=sizeof(char *) = 4 on a 32 bit implementation
for (int i = 0; i < length; i++)
{
printf("%c", source[i]);
}
}
sizeof(source)
returns sizeof a pointer as source is declared as char *.
Correct way to use it is strlen(source)
.
Next:
printf("%s",source[i]);
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.
Replace sizeof with strlen and it should work.
You need a pointer to the first char to have an ANSI string.
printf("%s", source + i);
will do the job
Plus, of course you should have meant strlen(source)
, not sizeof(source)
.