i have created an two dimensional array like this:
char string_y2m[2][8];
Then I just used memset() for initialize it by 0:
memset(&string_y2m, 0, sizeof(string_y2m));
Now I have to assign it some value but it's not working. I have assigned it like this:
string_y2m[2][8] = {"2011-1","2011-01"};
It's not working, same thing if I do at declaration itself, it works.
You cannot assign strings like that in C, when the target is a character array and you're not also declaring it.
In C, you need to use strcpy() to copy the string into the array, paying a lot of attention to the buffer sizes:
strcpy(string_y2m[0], "2011-1");
strcpy(string_y2m[1], "2011-01");
Or use snprintf() if you have it:
snprintf(string_y2m[0], sizeof string_y2m[0], "%s", "2011-1");
snprintf(string_y2m[1], sizeof string_y2m[1], "%s", "2011-01");
Also, there's no need to clear the space before writing the string there, since writing the string will set the characters to the required values.
Just don't use assignment but initialize the array correctly from the start:
char string_y2m[2][8] = {"2011-1","2011-01"};
This will initialize all characters that are not initialized explicitly to 0.
Related
How can I change a single character in a 2D array in C? I have tried but can't get it to compile...
char *words[50][20];
words[0][0] = "hello";
Now how can I change the 'h' to 'j' to make it "jello"?
You shouldn't try that because modifying a string literal is undefined behavior. Reasonable thing is to do this,
const char *p = "Hello";
words[0][0]=malloc(strlen(p)+1);
if(words[0][0]==NULL){
perror("malloc");
exit(1);
}
memcpy(words[0][0],p,strlen(p)+1);
Remember that you have declared a 2d array of char* - that's why allocated memory first using malloc and then copied the string literal. All this can be done with POSIX specified strdup
words[0][0]=strdup("Hello");
In C standard it is explicitly mentioned that modifying a string literal is undefined behavior. You should not use the code you have written for the very reason stated above.
After doing the changes you can make changes like words[0][0][0]='j' and that would be the correct code.
Also reconsider your design carefully. We seldom need 2d array of char* do you need it here? If not try to make design simpler with smaller constructs.
char *words[50];
And now you can make each pointer point to words which has different number of letters in it. The code would be quite similar to the earlier case - but instead of using words[0][0] you would use words[0], something like
words[0]=malloc(strlen(p)+1);
...
Or words[0]=strdup("Hello");.
The standard section which talks about string literal is given below, from 6.4.5p7 (note the array means the string literal)
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
I'm fairly new to the concept of pointers in C. Let's say I have two variables:
char *arch_file_name;
char *tmp_arch_file_name;
Now, I want to copy the value of arch_file_name to tmp_arch_file_name and add the word "tmp" to the end of it. I'm looking at them as strings, so I have:
strcpy(&tmp_arch_file_name, &arch_file_name);
strcat(tmp_arch_file_name, "tmp");
However, when strcat() is called, both of the variables change and are the same. I want one of them to change and the other to stay intact. I have to use pointers because I use the names later for the fopen(), rename() and delete() functions. How can I achieve this?
What you want is:
strcpy(tmp_arch_file_name, arch_file_name);
strcat(tmp_arch_file_name, "tmp");
You are just copying the pointers (and other random bits until you hit a 0 byte) in the original code, that's why they end up the same.
As shinkou correctly notes, make sure tmp_arch_file_name points to a buffer of sufficient size (it's not clear if you're doing this in your code). Simplest way is to do something like:
char buffer[256];
char* tmp_arch_file_name = buffer;
Before you use pointers, you need to allocate memory. Assuming that arch_file_name is assigned a value already, you should calculate the length of the result string, allocate memory, do strcpy, and then strcat, like this:
char *arch_file_name = "/temp/my.arch";
// Add lengths of the two strings together; add one for the \0 terminator:
char * tmp_arch_file_name = malloc((strlen(arch_file_name)+strlen("tmp")+1)*sizeof(char));
strcpy(tmp_arch_file_name, arch_file_name);
// ^ this and this ^ are pointers already; no ampersands!
strcat(tmp_arch_file_name, "tmp");
// use tmp_arch_file_name, and then...
free(tmp_arch_file_name);
First, you need to make sure those pointers actually point to valid memory. As they are, they're either NULL pointers or arbitrary values, neither of which will work very well:
char *arch_file_name = "somestring";
char tmp_arch_file_name[100]; // or malloc
Then you cpy and cat, but with the pointers, not pointers-to-the-pointers that you currently have:
strcpy (tmp_arch_file_name, arch_file_name); // i.e., no "&" chars
strcat (tmp_arch_file_name, "tmp");
Note that there is no bounds checking going on in this code - the sample doesn't need it since it's clear that all the strings will fit in the allocated buffers.
However, unless you totally control the data, a more robust solution would check sizes before blindly copying or appending. Since it's not directly related to the question, I won't add it in here, but it's something to be aware of.
The & operator is the address-of operator, that is it returns the address of a variable. However using it on a pointer returns the address of where the pointer is stored, not what it points to.
If I have a character pointer that contains NULL bytes is there any built in function I can use to find the length or will I just have to write my own function? Btw I'm using gcc.
EDIT:
Should have mentioned the character pointer was created using malloc().
If you have a pointer then the ONLY way to know the size is to store the size separately or have a unique value which terminates the string. (typically '\0') If you have neither of these, it simply cannot be done.
EDIT: since you have specified that you allocated the buffer using malloc then the answer is the paragraph above. You need to either remember how much you allocated with malloc or simply have a terminating value.
If you happen to have an array (like: char s[] = "hello\0world";) then you could resort to sizeof(s). But be very careful, the moment you try it with a pointer, you will get the size of the pointer, not the size of an array. (but strlen(s) would equal 5 since it counts up to the first '\0').
In addition, arrays decay to pointers when passed to functions. So if you pass the array to a function, you are back to square one.
NOTE:
void f(int *p) {}
and
void f(int p[]) {}
and
void f(int p[10]) {}
are all the same. In all 3 versions, p is a pointer, not an array.
How do you know where the string ends, if it contains NULL bytes as part of it? Certainly no built in function can work with strings like that. It'll interpret the first null byte as the end of the string.
If you want the length, you'll have to store it yourself. Keep in mind that no standard library string functions will work correctly on strings like these.
You'll need to keep track of the length yourself.
C strings are null terminated, meaning that the first null character signals the end of the string. All builtin string functions rely on this, so if you have a buffer that can contain NULLs as part of the data then you can't use them.
Since you're using malloc then you may need to keep track of two sizes: the size of your allocated buffer, and how many characters within that buffer constitute valid data.
char in[100], *temp[10],var[10][10];
int i, n = 0,
double val[10];
var[0][]="ANS";
I want to assign a string to var[0][0,1,2] which is 'ANS', but does not work and i cannot figure where i am wrong about this
Perhaps instead using,
strncpy(var[0], "ANS", 3);
You have sort of answered your own question. You want to assign var[0][0,1,2,3] to "ANS" right? Well "ANS" is an array of characters, ans[0,1,2,3] (don't forget the null terminator). So you have to assign each one individually. In C strings aren't a data type, they are just an array of other variables (chars to be exact). What you can do instead is:
strcpy(var[0], "ANS");
Which will do the byte-by-byte copy for you.
There are some pitfalls to strcpy, however. First, the destination char array (var[0] in this case) must be large enough to contain the string. It will not check this for you (it can't, actually) so if you are not careful you can cause a buffer overflow. Also, the source must be NULL terminated.
When you write
var[0][] = "ANS"
Compiler tries to assign "ANS" to var[0][0] which is a place for only one char.
Therefore, you should use strcpy function. strcpy will copy char-by-char.
Have an array of chars like char members[255]. How can I empty it completely without using a loop?
char members[255];
By "empty" I mean that if it had some values stored in it then it should not. For example if I do strcat then old value should not remain
members = "old value";
//empty it efficiently
strcat(members,"new"); // should return only new and not "old value new"
using
memset(members, 0, 255);
in general
memset(members, 0, sizeof members);
if the array is in scope, or
memset(members, 0, nMembers * (sizeof members[0]) );
if you only have the pointer value, and nMembers is the number of elements in the array.
EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset is overkill and just zeroing the first element suffices (as noted in other answers).
EDIT In order to use memset, you have to include string.h.
Depends on what you mean by 'empty':
members[0] = '\0';
Don't bother trying to zero-out your char array if you are dealing with strings. Below is a simple way to work with the char strings.
Copy (assign new string):
strcpy(members, "hello");
Concatenate (add the string):
strcat(members, " world");
Empty string:
members[0] = 0;
Simple like that.
char members[255] = {0};
EDIT: Given the most recent edit to the question, this will no longer work as there is no null termination - if you tried to print the array, you would get your characters followed by a number of non-human-readable characters. However, I'm leaving this answer here as community wiki for posterity.
char members[255] = { 0 };
That should work. According to the C Programming Language:
If the array has fixed size, the number of initializers may not exceed the number of members of the array; if there are fewer, the remaining members are initialized with 0.
This means that every element of the array will have a value of 0. I'm not sure if that is what you would consider "empty" or not, since 0 is a valid value for a char.
Use bzero(array name, no.of bytes to be cleared);
You cannot empty an array as such, it always contains the same amount of data.
In a bigger context the data in the array may represent an empty list of items, but that has to be defined in addition to the array. The most common ways to do this is to keep a count of valid items (see the answer by pmg) or for strings to terminate them with a zero character (the answer by Felix). There are also more complicated ways, for example a ring buffer uses two indices for the positions where data is added and removed.
members[0] = 0;
is enough, given your requirements.
Notice however this is not "emptying" the buffer. The memory is still allocated, valid character values may still exist in it, and so forth..
I'd go with
members_in_use = 0;
By "empty an array" if you mean reset to 0, then you can use bzero.
#include <strings.h>
void bzero(void *s, size_t n);
If you want to fill the array with some other default character then you may use memset function.
#include <string.h>
void *memset(void *s, int c, size_t n);
In this case just members[0] = 0 works.
Disclaimer: I don't usually program in C so there may be any syntax gotcha in my examples, but I hope the ideas I try to express are clear.
If "emptying" means "containing an empty string", you can just assign the first array item to zero, which will effectively make the array to contain an empry string:
members[0] = 0;
If "emptying" means "freeing the memory it is using", you should not use a fixed char array in the first place. Rather, you should define a pointer to char, and then do malloc / free (or string assignment) as appropriate.
An example using only static strings:
char* emptyString="";
char* members;
//Set string value
members = "old value";
//Empty string value
member = emptyString
//Will return just "new"
strcat(members,"new");
You can use the following instruction:
strcpy_s(members, "");