0

I'm new to C and i'm trying to store some strings inside a 2D array of chars.Here's what i have:

char strArray[100][100];
char input[100];
scanf("%s",&input);
strArray[i] = input; //this is where i get the incompatible types assignment error

As shown in the comment i get an incompatible types in assignment error.Do i need to use an array of char *strArray[100][100] ? Aren't strArray and input both of the same type (char [])? The one's 1D and the other is 2D obviously but i just didn't specify the 2nd dimension in the assignment since each string is stored in a new line. What am i doing wrong?

6
  • scanf("%s",&input); -> scanf("%s",input); , strArray[i] = input; -> strcpy(strArray[i], input); Commented Nov 7, 2018 at 22:38
  • @Osiris that's the same thing right? the array works as a pointer but & works too right? Commented Nov 7, 2018 at 22:39
  • input decays to a pointer to char while &input is a pointer to char[100]. So it is not the same, and %s expects a pointer to char. Commented Nov 7, 2018 at 22:39
  • Oh i see, and as for the strcpy() function, is that the only way for this "procedure" to be done? Can it also be done with pointers? Commented Nov 7, 2018 at 22:41
  • You can loop over the array and copy it element wise. Or you can use memcpy. You can not copy arrays with the = operator. Commented Nov 7, 2018 at 22:42

3 Answers 3

2

You'd have to use strcpy():

#include <stdio.h>
#include <string.h>

int main(void)
{
    char strArray[100][100];
    char input[100];
    scanf("%s", input);
    strcpy(strArray[0], input);
}

But never, really: never! use scanf() with "%s" without limiting the number of characters to read (field width):

 scanf("%99s", input);
Sign up to request clarification or add additional context in comments.

1 Comment

That's an awesome tip, i had no idea i could limit the number of chars that the user can enter by specifying a number between % and s within scanf. Awesome
0

You can use strcpy() to copy each char in input to strArray[i]. In this case you would use

strcpy(strArray[i], input);

Comments

0

In C, you cannot assign arrays in the sense of char input1[100], input2[100]; input1 = input2. You can just copy the contents using, for example, strcpy for strings or memcpy for arbitrary memory chunks.

So you'd have to write strcpy(strArray[i],input), provided that i is an integral value between 0 and 99 in your case.

Further, you'll have to omit the & in scanf("%s",&input) (i.e. write scanf("%s",input)), because input already decays to a pointer to char.

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.