简体   繁体   中英

Trouble with changing value of array in function using pointer

I am trying to write code that will prompt the user for a string, and then print the string. It will then use the function 'initialize' to change every value in the array to 'a' except the last value, which will be changed to '\\0'. The calling function will then print the updated string.

Here is the code I have:

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

void initialize(char (*firstString)[50]);

void main(void)
{
   char firstString[50];

    printf("Enter a string: ");
    scanf("%s", firstString);
    printf("%s", firstString);
    initialize(&firstString);
    printf("%s", firstString);
}

void
initialize(char (*firstString)[50])
{
    int i;
    for (i = 0; i < 50; i++) {
        *firstString[i] = 'a';
        *firstString[49] = '\0';
    }
}

Any help is appreciated.

EDIT:

Here is the working code. Thanks for the help!

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

void initialize(char firstString[50]);

void main(void)
{
   char firstString[50];

    printf("Enter a string: ");
    scanf("%s", firstString);
    printf("%s", firstString);
    initialize(firstString);
    printf("%s", firstString);
}

void
initialize(char firstString[50])
{
    int i;
    for (i = 0; i < 50; i++)
        memset(firstString, 'a', 49);
    firstString[49] = '\0';
}

[] has higher precedence than * so *firstString[x] is parsed as *(firstString[x]) . See C Operator Precedence .

So you need to write (*firstString)[x] to get the correct precedence.

Also, your function could be written simply as:

void
initialize(char (*firstString)[50])
{
    memset(firstString, 'a', 49);
    (*firstString)[49] = '\0';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM