Home > Software engineering >  How to print array using pointer variable in plain C
How to print array using pointer variable in plain C

Time:02-15

I'm doing some tests with functions that return arrays and, with some reading, I came with this:

#include <stdio.h>
#include <stdlib.h>

int i;

char * askData() {
    static char data[5];
    for(i = 0; i < 5; i  )
        scanf("%s", &data[i]);

    return data;
}

int main() {
    char* data = askData();
    
    printf("Flag 1\n");
    for(i = 0; i < 5; i  )
        printf("Loop %i: %s\n", i, &data[i]);

    printf("Flag 2\n");
}

What I want to do is to print each element from the pointer separately (much like an array, but I didn't used it because aparently a C function can't return an array).

Input:

Harry
Hermione
Ronald
Draco
Voldemort

Intended Output:

Flag 1
Loop 0: Harry
Loop 1: Hermione
Loop 2: Ronald
Loop 3: Draco
Loop 4: Voldemort
Flag 2

Current Output:

Flag 1
Loop 0: HHRDVoldemort
Loop 1: HRDVoldemort
Loop 2: RDVoldemort
Loop 3: DVoldemort
Loop 4: Voldemort
Flag 2

CodePudding user response:

in printf("Loop %i: %s\n", i,

  • Related