0

I am doing exercise 2-5 in K&R C and I decided to implement a function called getline(s, lc) where s is the string to concatenate the characters with and lc is an integer to count lines.

You guys might say that this is a possible duplicate but I am going to first explain how this question is different.

  1. Update (int) variable in C inside a function [duplicate] - This involves pointers but I am asking how I can update a variable without using pointers. I am a "n00b" at it.

  2. How to change variable? - This also involves pointers and doesn't have an accepted answer.

I want the program to run like this: (Overall)

String 0: the big brown fox jumped over lazy dog
String 1: lazy

First Occurrence: 29

I want my program to work that way in overall; Ask a user to input two string and if one character in String 1: matches in String 0: it will return the first occurrence of that character.

But let's focus on the first part where I implemented getline(s, lc). Putting a character in string is possible but I want to know if it's possible updating an integer variable.

As of now, this is how my program runs:

String 0: DEEP BLUE SKY
String 0: BLUE CAKE

The prompt where BLUE CAKE is should be String 1: not String 0: again.

/* getline: gets the character input and convert it into a string. */
void getline(char s[], int lc)
{
    int c, i, lim;

    lim = LIMIT;
    i = 0;

    printf("String %d: ", lc);
    while (lim > 0) {
        c = getchar();
        if (c == '\n' || c == EOF) {
            lim = 0;
        }
        else {
            s[i] = c;
            ++i;
       }
    }
    ++lc;
    s[i] = '\0';
}

And here's the link.

Is there a way to update an integer variable lc by 1 using a function without using pointers?

I want to solve this problem using what I learned so far in the book keeping away advanced topics.

Community
  • 1
  • 1

3 Answers3

0

You can have the function return the integer as its return value.

ojblass
  • 21,146
  • 22
  • 83
  • 132
0

You can either return lc from your function or use lc as a global variable (better to avoid using global variable).

haccks
  • 104,019
  • 25
  • 176
  • 264
0

You can by making the function return the value

int getline(char s[], int lc)
{
  ...

  return ++lc;
}

The string is passed by reference to the function so any changes you do to the string will anyway be visible outside the function. In effect char s[] passes the address where the string resides so you are free to change its contents inside your getline function.

The problem with your getline function is that it does not know the max size of the array since there is no such information available in the array itself. You should add the size as an argument as well to avoid memory overwrites.

e.g.

int getline(char s[], int maxlen, int lc)
AndersK
  • 35,813
  • 6
  • 60
  • 86