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?
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);
You can use strcpy() to copy each char in input to strArray[i]. In this case you would use
strcpy(strArray[i], input);
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.
Related
I expected to get errors in following code, but I did not. I did not use & sign. Also I am editing array of chars.
#include <stdio.h>
int main()
{
char name[10] ="yasser";
printf("%s\n",name);
// there is no error ,
// trying to edit array of chars,
// also did not use & sign.
scanf("%s",name);
// did not use strcpy function also.
printf("%s\n",name);
return 0;
}
I expected to get errors in following code, but I did not.I did not use & sign.
scanf("%s",name);
That's totally ok as name is already the address of the character array.
It sounds like you have several questions:
calling scanf("%s", name) should have given an error, since %s expects a pointer and name is an array? But as others have explained, when you use an array in an expression like this, what you always get (automatically) is a pointer to the array's first element, just as if you had written scanf("%s", &name[0]).
Having scanf write into name should have given an error, since name was initialized with a string constant? Well, that's how it was initialized, but name really is an array, so you're free to write to it (as long as you don't write more than 10 characters into it, of course). See more on this below.
Characters got copied around, even though you didn't call strcpy? No real surprise, there. Again, scanf just wrote into your array.
Let's take a slightly closer look at what you did write, and what you didn't write.
When you declare and initialize an array of char, it's completely different than when you declare and initialize a pointer to char. When you wrote
char name[10] = "yasser";
what the compiler did for you was sort of as if you had written
char name[10];
strcpy(name, "yasser");
That is, the compiler arranges to initialize the contents of the array with the characters from the string constant, but what you get is an ordinary, writable array (not an unwritable, constant string constant).
If, on the other hand, you had written
char *namep = "yasser";
scanf("%s", namep);
you would have gotten the problems you expected. In this case, namep is a pointer, not an array. It's initialized to point to the string constant "yasser", which is not writable. When scanf tried to write to this memory, you probably would have gotten an error.
When you pass arrays to functions in C, they decay to pointers to the first item.
Therefore for:
char name[] ="yasser";
scanf("%s", name) is the same as scanf("%s", &name[0]) and either of those invocations should send shivers down your spine, because unless you control what's on your stdin (which you usually don't), you're reading a potentially very long string into a limited buffer, which is a segmentation fault waiting to happen (or worse, undefined behavior).
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
char *myName = (char *) calloc(10, sizeof(char));
*(myName)='K'; *(myName+1)='h'; *(myName+2)='a'; *(myName+3)='l'; *(myName+4)='i'; *(myName+5)='d';
printf("%s\n",myName);
scanf("%s",myName);
printf("%s\n",myName);
return (EXIT_SUCCESS);
}
#include <stdio.h>
#include <string.h>
int main()//fonction principale
{
char name[10] ="yasser";
int longeur=0;
printf("%s\n",name);
scanf("%s",name);
longeur = strlen(name);
for (int i=0;i<longeur;i++) {
printf("%c",*(name+i));
}
return 0;}
I am trying to make an array with 10 pointers which will receive the input from scanf within a for loop. Then I want to call that list. However, I get a runtime error for memory:
#include <stdio.h>
int main(void) {
int i;
char * string[10];
//printf("%s", *string[0]);
for(i = 0; i<3; i++)
{
printf("what is string");
scanf("%s", string[i]);
printf("%s", string[i]);
}
return 0;
}
You need to think about the data structure with which you are attempting to store your strings.
char * string[10];
This declares an array of 10 elements of type "char *" or "pointer to a char".
Now think about what you are doing with this operation.
scanf("%s", string[i]);
You are using scanf to attempt to read user input. Does your function call make sense though?
The first parameter is your format string. "%s" makes sense because you want the user to provide you a string. Let's ignore the fact that you have not put any bounds on the length of that input for the moment.
Your second parameter needs to be be the variable where you want to store the input. You have provided "string[i]". Remember that in C, strings are just char arrays. However, your variable "string[i]" has the type "char *". This doesn't make sense. How can you store data of type "char array[]" in variable of type "char * array[]"? The types are different.
You need to create a buffer within which you can store your input string. Something like:
char buffer[256];
Then you call scanf like:
scanf("%s", buffer);
Keep in mind that this isn't the best idea because you don't know how many characters the user might enter. This will take the input character array and store them in a variable that correctly represents that data.
Note that this call would be safer:
fgets(buffer, sizeof(buffer)/sizeof(char), stdin);
fgets will read a fixed number of characters from the stream. In the above call I define that number by just taking the length of my buffer variable. I divide by sizeof(char) just to make sure that any strange representation issues where a char != 1 byte are taken care of. Also note that you will end up with the carraige return in your buffer (fgets will grab it).
Once you have your string in an appropriate variable, you can save it and get a pointer to a copy of that string with:
char * ptr = strdup(buffer);
This will create a new copy of the string stored in buffer and return a pointer to that new copy location. This pointer can then go into your array.
Note that you cannot just do:
string[i] = buffer
Because string[i] is just a pointer to the buffer variable...which will be overwritten during each iteration! You would end up with an array of pointers to the same variable, which would all end up giving you to the same string (the last input).
Put it all together in something like this:
char buffer[256];
printf("What is your string? ");
fgets(buffer, sizeof(buffer)/sizeof(char), stdin);
string[i] = strdup(buffer);
Because strdup() uses a malloc under the hood, you will need to free all your strings at the end of your program with:
int i = 0;
for(; i < sizeof(string)/sizeof(char *); i++) {
if(string[i]) free(string[i]);
}
You need to either allocate memeory dynamically or make your 2-d array:
char string[10][100];
You can do something like this to allocate memory -
for(i=0;i<10;i++){
string[i]=malloc(sizeof(char)*10);
}
So that your program does not give error.
But after this you have to free the memory allocated.
As i know, i can create an array with item inside such as:
char *test1[3]= {"arrtest","ao", "123"};
but how can i store my input into array like code above because i only can code it as
input[10];
scanf("%s",&input) or gets(input);
and it store each char into each space.
How can i store the input "HELLO" such that it stores into input[0] but now
H to input[0],E to input[1], and so on.
You need a 2 dimensional character array to have an array of strings:
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
Use a 2-dimensional array char input[3][10];
or
an array of char pointers (like char *input[3];) which should be allocated memory dynamically before any value is saved at those locations.
First Case, take input values as scanf("%s", input[0]);, similarly for input[1] and input[2]. Remember you can store a string of max size 10 (including '\0' character) in each input[i].
In second case, get input the same way as above, but allocate memory to each pointer input[i] using malloc before. Here you have flexibility of size for each string.
Did not really understand what you need. But here is what I guessed.
char *a[5];//array of five pointers
for(i=0;i<5;i++)// iterate the number of pointer times in the array
{
char input[10];// a local array variable
a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here
scanf("%s",input);//take the input from stdin
strcpy(a[i],input);//store the value in one of the pointer in the pointer array
}
try below code:
char *input[10];
input[0]=(char*)malloc(25);//mention the size you need..
scanf("%s",input[0]);
printf("%s",input[0]);
int main()
{
int n,j;
cin>>n;
char a[100][100];
for(int i=1;i<=n;i++){
j=1;
while(a[i][j]!=EOF){
a[i][j]=getchar();
j++;
}
}
This code inspired me on how to get my user input strings into an array. I'm new to C and to this board, my apologies if I'm not following some rules on how to post a comment. I'm trying to figure things out.
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
When the arguments of dyn_mat are constants, the code runs through without any error and s1 and s2 do store the input values.
#include<stdio.h>
int main(int argc, char const *argv[])
{
char *s1, *s2;
int n1=7, n2=8;
printf("Enter, %d \n", n1);
scanf("%s", s1);
scanf("%s", s2);
int dyn_mat[155][347];
return 0;
}
but with arguments as variables, say n1 and n2, scanf reading s1 gives segmentation fault.
The code simply has undefined behaviour, since s1 and s2 are not valid pointers. scanf expects a pointer to an array of chars that's large enough to hold the read data, and you are not providing such pointers.
The usual way would be something like this:
char s1[1000];
char s2[1000];
scanf("%s", s1);
scanf("%s", s2);
(Though you should use a safer version that specifies the available buffer size rather than hoping for the input to be sufficiently short; for example, scanf("%999s", s1);.)
why does c allow initialization of string without declaration?
There is no data type string in C.
In C one possible way to store a string of characters is using an array of characters, with the last element of this array carring a 0 to indicate the end of this string.
You program does not declare any array, but just pointers to characters, which have no memory assigned to which you copy data using scanf().
Your just lucky the program does not crash with the first call to scanf().
This is to convert from char pointer into char.
I followed the codes from another topic but it seems like it's not working to me.
I am using Open VMS Ansi C compiler for this. I don't know what's the difference with
another Platform.
main(){
char * field = "value1";
char c[100] = (char )field;
printf("c value is %s",&c);
}
the output of this is
c value is
which is unexpected for me I am expecting
c value is value1
hope you can help me.
strcpy(c, field);
You must be sure c has room for all the characters in field, including the NUL-terminator. It does in this case, but in general, you will need an if check.
EDIT: In C, you can not return an array from a function. If you need to allocate storage, but don't know the length, use malloc. E.g.:
size_t size = strlen(field) + 1; // If you don't know the source size.
char *c = malloc(size);
Then, use the same strcpy call as before.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char * field = "value";
char c[100]="";
strncpy(c,field,100);
printf("c value is %s",c);
return 0;
}
In C, the char type holds a single character, not a string. char c[100]; doesn't allocate a char of length 100, it allocates an array of 100 consecutive chars, each one byte long, and that array can hold a string.
So what you seem to want to do is to fill an array of chars with the same char values that are at the location pointed at by a char *. To do that, you can use strncpy() or any of several other functions:
strncpy(c,field,100); /* copy up to 100 chars from field to c */
c[99] = '\0'; /* ..and make sure the last char in c is '\0' */
..or use strcpy() since you know the string will fit in c (better in this case):
strcpy(c,field);
..or:
snprintf(c,100,"%s",field);