-1

I'm working on a program in which overwriting a part of a 2D array with a 1D string is a necessity for the algorithm.

The part that is supposed to do the overwriting is as follows:

char twoD[MAX][MAX];
int top=2;

int main(){
    char arr[MAX];
    func(arr);
}

void func(char newArr[]){
    strcpy(twoD[++top], newArr);
}

Where twoD and top are variables that are global variables.

Whenever the program reaches this part, it crashes.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • What's the error? What's an expected input/output? – Carcigenicate Nov 25 '16 at 13:03
  • 2
    What is `MAX`? Please show a [MCVE]. – Jabberwocky Nov 25 '16 at 13:03
  • The error is:"Program has stopped working". Some expected input: (5+3)*(7-3). – Anas Al-Masri Nov 25 '16 at 13:05
  • 3
    `strcpy` is designed to copy a null-terminated byte string: here the content of your array is uninitialized so the string is not null-terminated. As @user3121023 proposed, try `char arr[MAX] = {'\0'};` – rocambille Nov 25 '16 at 13:05
  • I tried initializing it. Now it crashes at the function call! – Anas Al-Masri Nov 25 '16 at 13:14
  • @AnasAl-Masri what is `MAX`. It may matter. Really. And you write _I tried initializing it_. Fine, but how did you initialize it ? Please show the complete code. Read un understand this: [MCVE]. Your example is minimal (that's good), but not complete (`MAX` is missing). – Jabberwocky Nov 25 '16 at 13:19
  • MAX is the highest array width throughout the whole program. I already defined it (#define MAX 15). – Anas Al-Masri Nov 25 '16 at 13:21
  • @AnasAl-Masri yes we know that is highest array width, but we didn't know it was 15, Did you try the code in my answer ? Does it work ? If not what happens? – Jabberwocky Nov 25 '16 at 13:22

2 Answers2

2

Take care of array boundaries.

char twoD[MAX][MAX];
int top=2;

int main(){
    char arr[MAX] = ""; //Initialize the string.
    func(arr);
}

void func(char newArr[]){
    if(++top < MAX) //Check if top has reached MAX.
    {
        strncpy(twoD[top], newArr, MAX-2); //At max copy string of length (MAX-2)+'\0'.
        twoD[top][MAX-1] = '\0';
    }
}
MayurK
  • 1,925
  • 14
  • 27
0

You didn't initialize arr

Try this:

int main() {
  char arr[MAX] = "HELLO";
  func(arr);

  printf("%s\n", twoD[3]);
}

The output will be:

Hello

Disclaimer: this is non error checking code thats serves only for demonstration purposes.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115