Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having trouble managing a array of strings.
This program is supposed to ask 3 names and then ask for a new name to rewrite the 1st name it got.
Then I print inside the function "change" the names[1] and names[2] which print incorrectly.
Finnaly at the End I print the 3 names without problems.

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

void change(char *names){
    printf("Insert New Name1: ");
    scanf("%s",&names[4]);
    strcpy(&names[0],&names[4]);
    printf("Test: %s\n",&names[1]);
    printf("Test: %s",&names[2]);
}

void main(void){
    char names[25][80];
    printf("Name 1: ");
    scanf("%s",&names[0]);
    printf("Name 2: ");
    scanf("%s",&names[1]);
    printf("Name 3: ");
    scanf("%s",&names[2]);
    change(names);
    printf("\nName1: %s",names[0]);
    printf("\nName2: %s",names[1]);
    printf("\nName3: %s",names[2]);
}



Terminal
Name 1: Jhon
Name 2: Wick
Name 3: Snow
Insert New Name1: John
Test: ohn
Test: hn
Name1: John
Name2: Wick
Name3: Snow
Process returned 12 (0xC)   execution time : 27.781 s
Press any key to continue.


What I have tried:

I tried to remove the "&" from the printfs but it crash.
Posted
Updated 23-Nov-21 13:21pm
v2

1 solution

The problem is the change function is not set up correctly. It needs to know the length of the strings. Your code accepted a single character pointer instead of an array of strings.

One way to do this is to define a type like this:
C
#define NAME_LENGTH 79

typedef char   NameString[ NAME_LENGTH+1 ];

void change( NameString names[] )
{
    printf( "Insert New Name1: " );
    scanf( "%s", names[4] );
    strcpy( names[0], names[4] );
    printf( "Test 1: %s\n", names[1] );
    printf( "Test 2: %s\n", names[2] );
}

void main(void)
{
    NameString names[25];
    printf("Name 1: ");
    scanf("%s", names[0] );
    printf("Name 2: ");
    scanf("%s", names[1] );
    printf("Name 3: ");
    scanf("%s", names[2] );

    change( names );

    printf("Name 1: %s\n", names[0]);
    printf("Name 2: %s\n", names[1]);
    printf("Name 3: %s\n", names[2]);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900