0

The title is pretty straight-forward. I want to access a char * string using pointer notation. I know I can print the string directly using the derefencing operator. For examsple, I have written the following program:

#include<stdio.h>

void printString(char * str){
    while(*str){
        printf("%c", *str);
        str++;
    }
}

int main(){
    char myString[] = "This is a String.";
    printString(myString);
    return 0;
}

This program prints the string correctly. However, if I change my printString function to following I get garbage:

void printString(char * str){
    int i = 0;
    while(*str){
        printf("%c", *(str+i));
        i++; str++;
    }
}

Why does this happen? How can I access the string using the array notation?

1
  • 1
    Why do you increment both i and str, one is sufficient. Commented Aug 13, 2014 at 18:03

1 Answer 1

5

First, you are incrementing both variables when you should only increment one.

Second, you should check the same condition that you are printing.

void printString(char * str){
    int i = 0;
    while(*(str+i)){
        printf("%c", *(str+i));
        i++;
    }
}

Third, based on your question title, you want array notation, which looks like the following, and not what you have.

void printString(char * str){
    int i = 0;
    while(str[i]){
        printf("%c", str[i]);
        i++;
    }
}

Fourth, you can make it more concise with a for loop.

void printString(char * str){
    int i;
    for(i = 0; str[i]; i++)
        printf("%c", str[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Since the title includes the phrase "array notation", might be worth showing how str[i] can be used, and is cleaner?
Thanks for mentioning the other array notation too! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.