0

I am trying to take in a char array that is oversized in order to place delimiters in it based on the variable maxSize

For example if the string "This is a message" is passed to the function along with a maxSize of 4 then the output should be "This, is ,a me,ssag,e"

char *placeDelimiter(char message[], int maxSize) {
  int msgSize = strlen(message);
  int delSize = (msgSize/maxSize);
  int remSize = msgSize%maxSize;
  int newSize = msgSize+delSize;
  if (remSize==0) delSize--; //removes delimiter if on end of char array
  char temp[newSize];
  int delPos = 0;
  for (int x=0;x<msgSize;x++) {
    if ((x+1)%maxSize == 0) temp[x] = ',';
    temp[x+delPos] = message[x];
    delPos = (x+1)/maxSize;
  } 
  return (char *)temp;
}

int main()
{
    char msg[] = "This is a message";
    char *p;
    p = placeDelimiter(msg, 4);
    printf("%s", p);
    return 0;
}

My problem is that I am getting the output "This i," from the input "This is a message" (From an online compiler). Can anyone explain to me what I am doing wrong and how to fix it?

0

1 Answer 1

1

char temp[newSize]; is a local variable to the function placeDelimiter(). Accessing it after the function has returned is Undefined behavior.

You should use dynamic memory allocation.

char* temp = malloc(newSize);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.