-1

The problem is that I don't actually know hot to deal with array of pointers, the way I do it, it pass to the position of the array the address, and so I got always in every position, the last input. But if I use the *operator, it only pass the first character.. so how I do it??

int main( void ) {

    void prompt_str( const char *str[], char *const copy ); //prototype

    const char *str[ 20 ]= { '\0' };
    const char *copy= 0;

    //prompt stringa
    prompt_str( str, &copy );

} //end main

void prompt_str( const char *str[], char *const copy ) { //definition

    size_t n_str= 0, i= 0;

    do {
        printf( "Insert a string\n:" );
        fgets( copy, 100, stdin );
        i= ( strlen( copy )- 1 ); //get length
        copy[ i ]= '\0'; //remove \n

        str[ n_str++ ]= copy; //put string into pointer of array

    } while ( n_str< 3 );

} 
dnt994
  • 31
  • 1
  • 1
  • 5

1 Answers1

1

You seem to have a misunderstanding of the pointer concept.

When you do

const char *copy= 0;

you only get a pointer. You don't get any memory for holding a string.

You can do

char copy[100];

instead. This will give you memory for holding a string (less than 100 characters). Further you can use copy as-if it is a pointer when calling a function.

Alternatively you can use dynamic memory like:

char* copy = malloc(100 * sizeof(char));  // Allocate memory

// ... code

free(copy);  // Release memory
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • it's not true.. infact when I debug, copy has the string I input in it. if I input "ciao", copy has "ciao", but, when I pass it to str, if I pass like in the code above, it's a pass by reference, so everytime I change copy, change the whole str. This is my problem, I want to pass whole copy by value. Just try my code and you'll see it. – dnt994 Nov 26 '16 at 17:19
  • @dnt994 Oh, yes it is true... Have you checked the warnings from the compiler? You have `incompatible pointer type` in the function call. BTW: Both "Keine Lust" and I have tried to help but instead of taking our input seriously, you just claim us to be wrong. Why? – Support Ukraine Nov 26 '16 at 17:44