Reputation: 13
#include <stdio.h>
struct Name {char d[11]};
int main (){
char str[11];
scanf("%s",str);
struct Name new = {str};
}
I want to initialize the Name structure new, but there is a warning: suggest braces around initialization of subobject.
How can I put the char array I read in my Name structure?
Upvotes: 1
Views: 971
Reputation: 16550
given the problems with the scanf()
given the probability of a buffer overflow/undefined behaviours, etc
I suggest using:
#include <stdio.h>
#define MAX_LEN (11)
// define the struct
struct Name {char d[MAX_LEN]};
// declare instance of the struct
struct Name myName;
int main ()
{
// remember: char *fgets(char *str, int n, FILE *stream)
if( fgets( myName.d, MAX_LEN, stdin ) )
{ // then fgets successful
printf( "%s\n", myName.d);
}
else
{ // else, fgets failed
printf( "fgets failed\n");
}
return( 0 );
} // end function: main
Upvotes: 0
Reputation: 56
When initialize struct in C it is a good idea to crate a function to do the initialization. I useally use a name line init_"name of struct". For you case a simple strncpy will init your string field. I use strncpy to avoid writing off the end of the string. Tip use a #define for setting the lengths of all you strings. Latter on when string lengths change you have one easy place to fix you problems. Here is you code with an init function
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NAME_LEN (11)
struct Name { char d[NAME_LEN]; };
void init_name(struct Name * n, char *s); // proto types should go in a h file
void init_name(struct Name * n, char *s)
{
strncpy(n->d, s, NAME_LEN); // copy s to name file d
}
int main(){
char str[11];
struct Name newName;
scanf("%s", str);
init_name(&newName, str);
}
Upvotes: 0
Reputation: 5946
You can do it like this:
#include <stdio.h>
struct Name {char d[11];};
int main (){
char str[11] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
scanf("%s",str);
// The below is C99 style.
struct Name new = { .d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}};
struct Name new2 = { .d = "hi mum"};
// Memcpy does the job as well
memcpy(new.d, str, sizeof(str));
}
EDIT:
If what you want is to copy whatever you got in your str
-buffer to Name
, you could do it like above. You could also do it like this.
struct Name new;
scanf("%s", new.d); /* Work directly on the structure. */
For more info on C99-style struct initialization, check this StackOverflow-question: C struct initialization with char array
Also heed R. Sahu's warning to not read more than the array can hold.
Upvotes: 0
Reputation: 206737
There are couple of ways:
int main ()
{
char str[11];
scanf("%10s",str); // Make sure you don't read more than
// what the array can hold.
struct Name name1 = {"name"}; // This works only if you use string literal.
struct Name name2;
strcpy(name2.d, str); // Use this when you want to copy from another variable.
}
Upvotes: 4