Frank Tocci
Frank Tocci

Reputation: 634

Using string as parameter for function

I am trying to use a function with a string as a parameter. I am running into a couple of error messages. First, it says that string[i] is not an array, pointer, or vector, despite the fact that string is a character array. Secondly, it says that I am doing a pointer to integer conversion. Here is my code:

#include <stdio.h>
#include <string.h>

void example (char string) {
    int i;
    for (i = 0; i < strlen(string); i++) {
        printf (string[i]);
    }
}

int main (void) {
    example("I like pie");
    return 0;
}

Upvotes: 1

Views: 149

Answers (4)

user-ag
user-ag

Reputation: 224

Your function example just receives a character. To get a string you can use a pointer. Also you can use "%s" format specifier in printf instead of using the for loop and strlen() function.

#include <stdio.h>
#include <string.h>

void example (char *string) {
    int i;
    printf ("%s\n",string);

}

Upvotes: 0

sps
sps

Reputation: 2720

You should use void example(char *string) instead of void example (char string).

#include <stdio.h>
#include <string.h>

void example (char *string) {
    int i;

    for (i = 0; i < strlen(string); i++) {
    printf ("%c",string[i]);
    }
    printf("\n");
}

int main (void) {
   example("I like pie");

   return 0;
}

Upvotes: 0

Gopi
Gopi

Reputation: 19864

Your API is wrong it should be

void example (char *string) { // string is a pointer 
    int i;
    size_t n = strlen(string);
    for (i = 0; i < n; i++) {
        printf ("%c",string[i]); // print character using %c
    }
}

Calculate the string length before the loop , calling strlen() in each iteration is not a good idea.

PS: what string points to is read-only you can't modify it

Upvotes: 4

iobender
iobender

Reputation: 3486

void example(char string) should be void example(char *string). You declared it to take a character, you want it to take a character pointer or array.

Also, you need to tell printf you are giving it a character: printf("%c", string[i]);.

Upvotes: 5

Related Questions