问题描述:

I'm using scanf to read a string and put it into a char*.

scanf("%s", &str);

printf("%c",str);

It works fine but I don't know how to access a specific character in that string as I would with a char[]. I have been trying to increment the address:

str += 1;

I have been messing around a bit but all I get is the first character or segfaults or bus errors. Is it possible to work with that string without copying into a char[]?

网友答案:

1)

  It works fine but I don't know how to access a specific character in that string as I would with a char[]

Just dereference the pointer-array with [] and access the character at position "i"

str[i]

2)

I have been messing around a bit but all I get is the first character or segfaults or bus errors

Yes - the arrayname itself is a pointer to the first character of the string

网友答案:

If str is declared as char * then this statement

scanf("%s", &str);

is incorrect. There has to be

scanf("%s", str);

And the next statement

printf("%c",str);

is also incorrect. There has to be

printf("%c", *str);

If you want to output some other character in the character array using pointer char * then you can write either

printf( "%c", *( str + n ) );

or

printf( "%c", str[n] );

or even as

printf( "%c", n[str] );

where n some integer value that less then strlen( str )

Take into account that str shall point to some allocated memory. Otherwise the program will have undefined behaviour.

相关阅读:
Top