V
V
Vadim kyklaed2018-02-28 12:17:54
C++ / C#
Vadim kyklaed, 2018-02-28 12:17:54

I change the value by reference, what is my mistake?

Good afternoon. I pass the value by reference to the function and change this value in the function . after I need to use this value after the function is completed. what is my mistake? I get the value N ==0 , so the for loop doesn't work.

#include <iostream>
#include <conio.h>

using namespace std;

void conct_str(char str[],int& N){
  char c;
  char b;
  cin.get(c);
  cin.get(b);
  while (c != '\n'){
    str[N]=c;
    N++;
    cin.get(c);
    }
  while (b != '\n'){
    str[N]=b;
    N++;
    cin.get(b);
    }	
    
  str[N]='\0';
  
  }
  

int main(){
  
  int N=0;
  char str[N];
  conct_str(str, N);
  for (int i=0;i<N;i++){
    cout<<str[i];
  }
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-02-28
@kyklaed

Has nothing to do with your question, but:
In main, you allocate memory for an array of 0 elements.
intN=0;
charstr[N];
How much memory do you think will be allocated for this array?
Also, you probably think that by incrementing N you increase the size of the array? This is not true - increasing N does not affect str in any way.
PS: it seems that VLA for beginners is evil.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question