is it possible to initialise a char array separately from where it is declared without using either a for loop or initialising the array character by character?
7 replies to this topic
#1
Posted 21 March 2011 - 03:36 AM
|
|
|
#2
Posted 21 March 2011 - 03:55 AM
char *str; str = "hello";
#3
Posted 21 March 2011 - 04:05 AM
Here are some of varying levels of usefulness and complexity:
char foo1[] = "abc"; //automatically define null ending
char foo2[4] = "abc\0"; //manually define it
char foo3[4] = {'a', 'a' + 1, 'c', 0}; //automatic conversion to chars, then char array
printf("%s, %s, %s\n", foo1, foo2, foo3);The third one works because ASCII 'a' + 1 is ASCII 'b', and 0 is the same as char \0 (but not '0')
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
#4
Posted 22 March 2011 - 04:47 AM
Alexander said:
Here are some of varying levels of usefulness and complexity:
char foo1[] = "abc"; //automatically define null ending
char foo2[4] = "abc\0"; //manually define it
char foo3[4] = {'a', 'a' + 1, 'c', 0}; //automatic conversion to chars, then char array
printf("%s, %s, %s\n", foo1, foo2, foo3);The third one works because ASCII 'a' + 1 is ASCII 'b', and 0 is the same as char \0 (but not '0')
#5
Posted 22 March 2011 - 05:07 AM
Use strncpy()
Just be sure to include string.h
char[10] str; ... strncpy(str, "Hello", 10);
Just be sure to include string.h
#6
Posted 22 March 2011 - 05:23 AM
The most simple way is to access it as a pointer, an example showing this:
char somestring[32];
char *ptr = somestring;
if(!ptr) {
fprintf(stderr, "Pointing to NULL buffer");
}
strncpy(ptr, "foobar\0", sizeof(somestring));
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
#7
Posted 22 March 2011 - 07:58 PM
WARNING:
gregwarner wrote:
gregwarner wrote:
char[10] str;This is not valid C, it is Java. In C, the array type specifier has the same syntax, precedence and notation as the array subscript operator.
char str[10];
#8
Posted 23 March 2011 - 05:17 AM
So sorry about that. You're absolutely right. I code in Java at work, and with my head in the Java clouds all day long, it's easy to accidentally cross between the two languages. Good spotting my mistake. :)
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









