Pervy Sage
Pervy Sage

Reputation: 871

How can I access a char * using the array notation in C?

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?

Upvotes: 0

Views: 223

Answers (1)

merlin2011
merlin2011

Reputation: 75545

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]);
}

Upvotes: 5

Related Questions