TransWikia.com

itterations on a string, 'expression must have a pointer-to-object type' error

Stack Overflow Asked by Tom Arica on December 2, 2020

I have a problem doing itterations on a string.

function input:

  1. a string of numbers with no spaces in between, in the range of [-9,9], and up to 10 numbers (means maximum 20 chars long if every number is negative).
  2. the size of the string.

the function needs to create an array of the numbers.

for example if I get the input "809-2-3", my new array needs to be – [8,0,9,-2,-3].

in my code, I get the error ‘expression must have a pointer-to-object type’, and I dont understand it.

this is the code I made:


void separate_nums(char str, int str_len)
{
   int new_arr[20];
   int i;
   for (i = 0; i <= str_len - 1; i++)//run through the string
   {
       if (str[i] == '-') //if the char is -, take minus of the next char. than increase index by one so youll get to the next number
       {
           new_arr[i] = -str[i + 1];
           i++;
       }
       else
           new_arr[i] = str[i];
   }
}

Thank you!

One Answer

First, an array is needed.

  1. Count the number of digits (n).
  2. Allocate an array which can hold n numbers.

Next, it's just a question of looking at the characters of the string one at a time. Any time a - is encountered, simply use the next character, but negate it.

  1. Initialize a variable identifying the next character to parse.
  2. Loop for each element of the array,
    1. Assume the number isn't negative.
    2. If the next character is a -,
      1. The number is negative.
      2. Move to the next character.
    3. Convert the next digit to a number.
    4. If the number should be negative,
      1. Negate the number.
    5. Store the number in the current array element.
    6. Move to the next character.

Of course, we need to make sure the user doesn't provide garbage. This is left to you to handle.

Answered by ikegami on December 2, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP