0

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';
}
8
  • 1
    You should get a warning with -Wall -Wextra, that tells you what the problem is. Commented Apr 25, 2016 at 12:22
  • *firstString[i] and precedence.... Commented Apr 25, 2016 at 12:25
  • *firstSring[i] is a ** pointer use only 1 pointer Commented Apr 25, 2016 at 12:26
  • 2
    Thou shalt not compile without -Wall -Werror. Commented Apr 25, 2016 at 12:30
  • 1
    Lastly, do you really need to set the string terminator for all iterations of the loop? And why not use memset to set all the bytes instead of your own loop? Commented Apr 25, 2016 at 12:31

1 Answer 1

2

[] 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';
}
Sign up to request clarification or add additional context in comments.

Comments