I've already searched for the right answer in several threads, but I couldn't find the exact problem that I have anywhere:
In my program, I've created an array which I'd like to fill with certain dates within a loop. The problem is the assignment - as I don't really know how to describe it (I've got absolutely no experience in programming with C), I'll post a bit of the code:
int *array[] = malloc (w*h*sizeof(int));
array[i] = (SDL_MapRGB(fmt, red, green, blue));
So the first line creates my array and in the second line, I actually wanted to write the result of the function "SDL_MapRGB", which is an integer, in the i-th place in this array. (As this is part of the loop, at the end of it, I would have the whole array filled if it works.)
And this is the error I'm getting:
error: assignment makes pointer from integer without a cast [-Werror]
Does anybody know how I could fix that? I still (after reading in old threads) don't understand what that means. I would be very grateful for any help :)
Because your declaration is wrong. int *array[] is an array of pointers. Since you use a one-dimensional array, all you have to do is int *array, i. e. drop the brackets.
array[i] is a pointer while the function SDL_MapRGB() returns an integer which is the reason for the warning.
Change your array declaration to:
int *array = malloc (w*h*sizeof(int));
Related
I got a task to modify the content of a 2-dimensional array int[5][5], I was given the definition int *a[5][5] and ordered to use a int** (the pointer of a pointer) to handle this task.
I'm now wondering the meaning of this int *a[5][5], how can I understand the meaning of this and similar definitions?
int *a[5][5] is a 2D array of pointers. A pointer-to-pointer can be used to point at any pointer item in this array.
A for how to understand the declaration, everything left of the variable name is the type of each item in the array, in this case int*.
You could also use this site. It works for many C declarations, but not all.
It is nothing but a Matrix of Pointers
In fact there are meny questions on stackoverflow on these. Please refer cdecl.org
I am writing a C program that uses an array of integers which is a part of a structure. The structure is:
struct test
{
int *ques;
int a;
int b;
int len; // len is the length of the array defined in the structure as ques.
};
In a function after this declaration I have assigned a value to the len as:
cases[0].len=5; // here cases is an array of the type struct test.
and then I have used malloc to allocate memory to the array member ques as follows:
cases[0].ques=(int *)malloc(cases[counter].len*sizeof(int));
After that I have tried to fill in the array ques as follows:
cases[0].ques[5]={-7,-6,-5,-4,-3};
and while compiling I get an error at the above line stating that:
maxmin.c(47) : error C2059: syntax error : '{'
Can you please help me out?
This is invalid: cases[0].ques[5]={-7,-6,-5,-4,-3};
You can initialize an array in C this way, only at the time of declaration of array.
To fill in the values at this point in your C program you should use for loop to fill every index separately.
Right now the C compiler parses this statement as:
Value of index 5 of array ques at index 0 of structure array cases of type struct test is {-7,-6,-5,-4,-3}, which is certainly invalid since you cannot use { while assigning a value to a variable.
Update at OP's comment:
You can keep all the values in temp array say int temp[50] = {...}; then after allocating space to ques you can use memcpy function to copy len number of values to ques.
If you have C99 or C11, you can use a compound literal in conjunction with memcpy() or memmove() to initialize the new array:
memmove(&cases[0].ques, (int []){-7,-6,-5,-4,-3}, 5 * sizeof(int));
This also fixes the problem that you allocate cases[0].ques as a pointer to 5 integers, but you then try to assign to a single element that is beyond the end of the allocated array. The code is also inconsistent in that most of it references cases[0] but the malloc() call references cases[count] in the argument list. Not automatically wrong, but definitely unusual.
The array literal can be as big as you need. The only tricky bit is the size argument (third argument) to memmove(). I ducked fast on that; repeating the compound literal doesn't feel like the right move, but manually counting isn't a good solution either.
Well, you could if memmove() wasn't a macro that objected to being given 7 arguments instead of 3 (GCC 4.8.2 on Mac OS X 10.9.2)!
(memmove)(&cases[0].ques, (int []){-7,-6,-5,-4,-3}, 5 * sizeof(int));
memmove(&cases[0].ques, ((int []){-7,-6,-5,-4,-3}), 5 * sizeof(int));
The first invokes the function memmove(), not a macro. The second creates a single argument by wrapping parentheses around the compound literal. Both compile.
Note that although the compound literal looks like a cast and a brace-initializer, I'm not sure it is strictly a cast — it is best not to think of it as a cast but as a compound literal.
Incidentally, if the objective is to add N random values to an array of N integers (as mentioned in a comment to one of the other answers), then you won't want to use this technique — the integers in the example are implausible as a random sequence. If you do want 50 random numbers in some range, you'll use a random number generator (possibly rand(), possibly
lrand48(), possibly something else) to create the values in an appropriate range, using a simple for loop to initialize the correct number of array elements.
assign value to each array element as,
cases[0].ques[0]=-7
cases[0].ques[1]=-6
...
cases[0].ques[5]=-3
since you are assigning the value after declaration. C allows {} use for initializing array at the time of declaration. not after that.
I hope you realize why cases[0].ques[5] is wrong.
int arr[5] = {1,2,3,4,5};
The above code works because you are doing the initialization of array at the declaration time.
If you have
int arr[5];
arr[5] = {1,2,3,4,5}; // THIS WONT WORK
Here, you'll have to use for loop and fill each index.
also, when you do
int arr[5];
arr[5] = {1,2,3,4,5};
In the above code, what you are trying to do is, put some value in arr[5]. That is just one index of the entire array.
Additionally, as the comment suggests, arr[5] is the 6th element in the array of size 5. Now although it won't give error, but be prepared to get some unexpected results. :)
ques[5] is an int, you cannot assign an array to it
Also, C doesn't allow to assignment to multiple elements in an array like that. You can only do it at initialization. So create a new array and initialize with those 5 elements and copy it to your destination with memcpy() or memmove()
int[] tmp = {-7,-6,-5,-4,-3};
memcpy(cases[0].ques, tmp, 5*sizeof(int));
Alternatively you can assign values to ques[i] separately
Lot of time I do not program in C, but I think the only situation in which you can do a complete array declaration is in the time that you declare it:
int a[] = {...}
But not this way:
int a[5];
a = {...};
Also, in your case, you are doing
int a[5] = {...}
and this means that you are trying to assign an array to an integer.
Also, it's better if you do not do a cast in the malloc call:
cases[0].ques = malloc(cases[counter].len * sizeof(int));
cases[0].ques[5]={-7,-6,-5,-4,-3};
You cannot do this, this initializer only valid when you define an array.
You should do something like:
for (start = -7, i = 0; i < cases[0].len; i++, start++) {
cases[0].ques[i] = start;
}
I got strucure
typedef struct
{char *cells;}
Map;
and cells suppose to be pointer to array of rows(in rows are integers on every position).
I don't know how to access for example to number on 3. position in 2. row.
I have stared with some array[3][3], but I don't know how to connect them with this struct.
I tried
Map nextmap;
nextmap.cells[0] = array[0][0];
But I got only first number, which is clear. How can I get to other positions?
Thanks in advance.
EDIT: renaming the structure ..
.
When you did Map nextmap;, you created an uninitialized Map struct. When you did nextmap.cells[0] = array[0][0]; you dereferenced (i.e. followed) the uninitialized pointer, and stored a value at the random memory it points at.
If you want to initialize the cells structure, you can do something as simple as nextmap.cells = array[0]; That will cause nextmap.cells to point at array. Note that it's not copying the contents; just pointing at them. That means that if you change the values through cells, you'll be modifying the values in arrays.
(Also, using 'new' as a variable name is perfectly acceptable in C, but you're likely to confuse any C++ programmers reading your code, since 'new' is an operator in that language.)
new now changed to nextmap in question
Edited to correct the type mismatch in nextmap.cells assignment.
Given an array char array[][NumberOfColumns] (the first dimension is irrelevant and is omitted here; it would be needed when the array is defined), you can set a pointer to the first element of the array with:
nextmap.cells = &array[0][0];
Then you can access an element in the array, array[i][j], by calculating its position within the array, with either of these two expressions:
*(nextmap.cells + i*NumberOfColumns + j)
nextmap.cells[i*NumberOfColumns + j]
Two-dimensional arrays generally ought to be addressed as two-dimensional arrays. Calculating the position manually is poor practice if done without good reason. If this school assignment did not have a good reason for this, then it is a bad assignment.
First of all new is not a good name for a variable.
new now changed to nextmap in question
Second of all in your case cells should be a double pointer, like this
char ** cells;
Or a pointer to a 2D array, like
char (*cells)[N][N];
where N is a constant you want to use.
I am working on a project for school and I have managed to figure out a work around by doing something really clunky with my code. I have a structure that holds multiple fields, and I am trying to access the following field (as it is declared in the struct named current_event).
int *number_of_couples;
and later down into the program I call this value so I can dynamically allocate an array based on this *number_of_couples field. Essentially I am trying to use this as a "length" operator as C does not have (good) solution.
Before I was trying to implement the following code:
int *permutable_array;
permutable_array = malloc((current_event->number_of_couples) * sizeof(int)); //Line 91
if(permutable_array == NULL){
panic("permutable_array"); //Ensures that Malloc was successful.
}
which would in turn throw the following error:
Line 91: error: invalid operands to binary * (have 'int *' and 'unsigned int')
I have made a very sloppy work around because at this point I just want to get the program working (hour three of pure programming! rock on!). So I implemented:
int *permutable_array;
int avoid_my_bug = (int) current_event->number_of_couples;
permutable_array = malloc(avoid_my_bug * sizeof(int));
if(permutable_array == NULL){
panic("permutable_array");
}
Which works. Now I somewhat understand the error that it is telling me. I suspect it has something to do with the fact that I stored the value of number_of_couples as a pointer within current_event, which is also a pointer. So really if the value of number_of_couples is 4, the path the program makes to get to that value is:
ptr_to_current_event -> ptr_to_number_of_couples -> 4
I can use my sloppy work-around, but it is obvious that I am doing it to avoid a bug. I would rather learn why the code will not compile. I also tried doing:
permutable_array = malloc((*current_event->number_of_couples) * sizeof(int)); //Line 91
which should have dereferenced the pointer returned by current_event->number_of_couples, however it crashes. Any solutions?
*EDIT*
It is initialized by the following line of code:
fscanf(input_file, "%i", ¤t_event->number_of_couples);
and is referenced at least three times (there is a valid int value stored in it) by the program before reaching my code. Remember, the second bit works, therefore it is definitely initialized.
You shouldn't be storing integer values inside pointers. Pointers are made to point at things, you should rarely need to convert a pointer to an integer type. If you do you should use either the uintptr_t or intptr_t types.
You should either dereference the pointer (assuming it is pointing at a valid int) or change the type of number_of_couples so that it is not a pointer. If you leave it as a pointer, you must ensure it is pointing to a valid int object before trying to dereference it, but based on your usage and context above, it doesn't need to be a pointer.
You must dereference the pointer to int
*(current_event->number_of_couples) * sizeof(int)
Casting the pointer to an int, will give you the address of number_of_couples as an integer. This might be some arbitrary large number like 0xf97e1892, for example.
The crash could be a result of number_of_couples not being initialized. You must allocate memory for this pointer. If it is not initialized, it will point to an arbitrary location.
If you initialize it with an integer number_of_couples = 5, it will point to invalid memory. The pointer is only valid, if you allocate memory from the heap or point to another integer variable.
All in all, it seems in your case it is best to define number_of_couples as an int and avoid all the potential pitfalls.
int number_of_couples;
Then, you can just allocate the memory as in your first example.
You should use *(current_event->number_of_couples), that way you will get the value to which pointer is pointing. If you do not use * you will get an address of pointer which you can cast to int but that is not what you want.
Try putting parentheses in your code around current_event->number_of_couples and then use *. If it doesnt help then something else is causing crashing.
If your code is crashing when you dereference this pointer, the chances are that it is pointing to invalid or uninitialised memory. You don't indicate in your question where this gets initialised, but dereferencing an uninitialised pointer is asking for trouble - look into where it gets initialised and if it is pointing to dynamic memory or not.
Yesterday while I was coding in C, my friend asked me pointing to a variable is it pointer or a variable ? I stucked up for a while. I didnt find an aswer to it , I just have to go back and search it and tell him.But I was thinking is there any function to differentiate them.
Can we differentiate a variable against a pointer variable
int a;
sizeof(a); // gives 2 bytes
int *b;
sizeof(b); // gives 2 bytes
// if we use sizeof() we get same answer and we cant say which is pointer
// and which is a variable
Is there a way to find out a variable is a normal variable or a pointer? I mean can someone say that it is a pointer or a variable after looking at your variable that you have declared at the beginning and then going down 1000 lines of your code?
After the comment
I wanted to say explicitly it's a 16 bit system architecture.
First, the question "Is it a pointer or a variable" doesn't make much sense. A pointer variable is a variable, just as an integer variable, or an array variable, is a variable.
So the real question is whether something is a pointer or not.
No, there's no function that can tell you whether something is a pointer or not. And if you think about it, in a statically typed language like C, there can't be. Functions take arguments of certain specified types. You can't pass a variable to a function unless the type (pointer or otherwise) is correct in the first place.
You mean differentiate them at run time without seeing the code? No, you can't. Pointers are variables that hold memory address. You can't check it at run time. That means, there is no such function isPointer(n) that will return true/false based on parameter n.
You can deduce the type from the use.
For example:
char* c;
...
c[0] = 'a';
*c = 'a';
Indexing and dereferencing would let you know it's a pointer to something (or it's an array if defined as char c[SOME_POSITIVE_NUMBER];).
Also, things like memset(c,...), memcpy(c,...) will suggest that c is a pointer (array).
OTOH, you can't normally do with pointers most of arithmetic, so, if you see something like
x = c * 2;
y = 3 / c;
z = c << 1;
w = 1 & c;
then c is not a pointer (array).
Three things:
What platform are you using where sizeof(int) returns 2? Seriously
Pointers are types. A pointer to an int is a type, just like an int is. The sizes of a type and a pointer to that type are sometimes equal but not directly related; for instance, a pointer to a double (on my machine, at least) has size 4 bytes while a double has size 8 bytes. sizeof() would be a very poor test, even if there was a situation where such a test would be appropriate (there isn't).
C is a strictly typed language, and your question doesn't really make sense in that context. As the programmer, you know exactly what a is and you will use it as such.
If you'd like to be able to tell whether a variable is a pointer or not when you see it in the source code, but without going back to look at the declaration, a common approach is to indicate it in the way you name your variables. For example, you might put a 'p' at the beginning of the names of pointers:
int *pValue; /* starts with 'p' for 'pointer' */
int iOther; /* 'i' for 'integer' */
...or even:
int *piSomething; /* 'pi' for 'Pointer to Integer' */
This makes it easy to tell the types when you see the variable in your code. Some people use quite a range of prefixes, to distinguish quite a range of types.
Try looking up "Hungarian notation" for examples.
no , you can't.
and what is the usage, as each time u run the code the pointer address will be different ?? however u can subtract two pointers and also can get the memory address value of any pointer.