Being able to define an array e.g.
int a[] = {1,2,3};
is very convenient, however, the array a is an r-value so I can't subsequently change the values in a, e.g.
a[] = {4,5,6};
The context for wanting to do this is writing a bunch of unit tests where I am feeding in arrays to functions and testing the outputs. I'm running tests on the same function with different inputs and would like to avoid having to have unique names for my input arrays, e.g. I'm having to do this:
int test1_a[] = {1,2,3};
/* calls to functions */
int test2_a[] = {4,5,6};
/* calls to functions */
Also, if I want to pass a pointer to an array into a function I have to 1st cast it like this:
int a[] = {1,2,3};
int *b = a;
my_func(&b);
passing a pointer to an r-value like this doesn't work:
my_func(&a);
My question is whether there is any other way to easily initialise an array of values without suffering from these limitations? (particularly with a view to making it easy to write many similar unit tests without each test having a unique set of array names)
If you already have the values you want to pass to the functions, why not use a multi-dimensional array?
int a[][] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
}
for (int i = 0; i < 2; i++)
{
/* Call functions with 'a[i]' as argument */
}
Also, if the functions you call expect an array, and you have a e.g. int a[] = {...}; int *b = a;, then don't call them with &b. Using &b passes the address of the pointer, not what it points to.
If i have understood your question properly.I guess the following should solve your problem.
memcpy(a, (int[]){3, 2, 1}, sizeof a);
Only if your c compiler supports compound literals(c99 onwards).
To specify the standard, gcc can be invoked as "gcc -std=c99 -Wall -pedantic".
Here's one option:
#include <stdio.h>
#include <stdarg.h>
void ReinitArray(int* p, size_t cnt, ...)
{
va_list ap;
va_start(ap, cnt);
while (cnt--)
{
*p++ = va_arg(ap, int);
}
va_end(ap);
}
int array[5] = { 1, 2, 3, 4, 5 };
int main(void)
{
size_t i;
printf("array[5]=");
for (i = 0; i < 5; i++) printf("%d ", array[i]);
printf("\n");
ReinitArray(array, 5, 11, 22, 33, 44, 55);
printf("array[5]=");
for (i = 0; i < 5; i++) printf("%d ", array[i]);
printf("\n");
return 0;
}
Output:
array[5]=1 2 3 4 5
array[5]=11 22 33 44 55
And you can simply write my_func(a); where a is an array name. This will be equivalent to passing &a[0], the address of the very first array element. You can't pass entire arrays directly as function parameters in C.
Related
I am trying to solve a question.
If in array a number is duplicated I make him 0. My code is throwing an error could you please help me ?
#include <stdio.h>
int main() {
int a[] = {-3, -2, -1, -7, -3, 2, 3, 4, 2, 7, 10, 3};
int length = 12;
int zero_duplicates(int laenge, int *a) {
int zero[] = {};
int k = 0;
int j = 1;
for(int x=0; x<laenge; x++)
{
if (zero[*a] == 1) {
*a = 0;
} else {
zero[*a] = 1;
k++;
}
a++;
}
return k;
}
int count = zero_duplicates(length, a);
printf("%d -- ", count);
for(int i = 0; i < length; i++) printf(" %i ", a[i]);
return 0;
}
This ...
int zero[] = {};
... is not a valid array declaration in C. If your compiler accepts it as an extension then it ought at least to be emitting a warning, and even then it probably doesn't mean what you think it means. Specifically, among the most likely extensions would be to interpret that as declaring a zero-length array (which also would constitute an extension), such that accessing any element overruns the array bounds.
Moreover, no matter how long the array is, if any of the elements of the input array are negative (as is the case in the example) then zero[*a] will constitute an out-of-bounds access when a points to one of those elements.
Overall, you need a different approach. What you're trying to do is not viable.
As a separate matter, C does not support nested functions, so your code is relying on yet another extension in that respect. This particular issue can be resolved by lifting the nested function out of main(), however, putting it above instead of inside.
Trying to work on leetcode #497 in C on my vscode. When writing main(), I am not sure how to deal with int** that leetcode provides. Is it possible to pass a 2D array using int**?
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int rectsSize;
int * rectsColSize;
int** rects;
} Solution;
int points[100];
Solution* solutionCreate(int** rects, int rectsSize, int* rectsColSize) {
Solution* sol = malloc(sizeof(Solution));
sol->rects = rects;
sol->rectsSize = rectsSize;
sol->rectsColSize = rectsColSize;
//some codes
}
return sol;
}
int* solutionPick(Solution* obj, int* retSize) {
//some codes
return ret;
}
void solutionFree(Solution* obj) {
free(obj);
}
int main(void)
{
int rects[2][4] = {{1, 1, 5, 5}, {6, 6, 9, 9}};
int rectsSize = 2;
int rectsColSize = 4;
int retSize;
Solution* obj = solutionCreate(rects, rectsSize, &rectsColSize);
int* param_1 = malloc(sizeof(int));
param_1 = solutionPick(obj, &retSize);
solutionFree(obj);
return 0;
}
While in general there are many different ways to handle 2D array, the simple answer is no. There is a lot of info about 2d arrays in C: 1, 2, 3, etc. In principle, when dealing with 2d arrays, every dimension except first to the left needs to be specified exactly. In your case, every rectangle is defined by 4 integers, so instead int** rects consider int*[4] rects. This makes rectsColSize useless, because now each column has constant size of 4 ints.
Just for completness: what you are trying to do is second approach to arrays, where each column has independent size, and (usually) additional malloc call. While this approach is also valid and requires int** type, it is not needed for your task. Nice description of the difference here.
Edit
Here is how to loop through 2d arrays:
#define col 4
void print_2d(int (*a)[col], int aSize){
for(size_t i = 0; i < aSize; i++){
for(size_t j = 0; j < col; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
and here for int**:
void print_pp(int** a, int aSize, int* aiSize){
for(size_t i = 0; i < aSize; i++){
for(size_t j = 0; j < aiSize[i]; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
It seems that you want to convert int*[4] to int**, or more precisely, int*[4] arr2d with it's size int arr2dSize to structure Solution. In that case, here is wrapper to solutionCreate.
Solution* solutionCreateWrap(int (*arr2d)[4], int arr2dSize) {
int* rectsColSize = malloc(arr2dSize * sizeof(int));
int** rects = malloc(arr2dSize * sizeof(int*));
size_t arr2dMem = arr2dSize * 4 * sizeof(int);
rects[0] = malloc(arr2dMem);
memcpy(rects[0], arr2d, arr2dMem);
rectsColSize[0] = 4;
for(size_t i = 1; i < arr2dSize; i++){
rects[i] = rects[0] + i*4;
rectsColSize[i] = 4;
}
sol->rects = rects;
sol->rectsSize = rectsSize;
sol->rectsColSize = rectsColSize;
//some codes
}
return solutionCreate(rects, arr2dSize, rectsColSize);
}
Now for int rects[2][4] = {{1, 1, 5, 5}, {6, 6, 9, 9}}; call solutionCreateWrap(rects, 2) will return initialised structure Solution. It looks gruesome, and it's details are even worse, so if it just works, you may skip the explanation. Understanding low level C details isn't neccesarily to write in it, and this (or any other) explanation cannot possibly cover this matter, so don't be discouraged, if you won't get it all.
arr2d is contiguous block of memory of arr2dSize*4 integers. When multiplied by sizeof(int) we get size in bytes - arr2dMem in my code. Declaration int (*arr2d)[4] means, that arr2d is of type int*[4]. Knowing this we can cast it to int* like so: int* arr = (int*)arr2d and expression arr2d[i][j] is translated as arr[i*4+j].
The translation to rects is as follows; int** is array of pointers, so every rect[i] has to be pointer to i-th row of arr2d. Knowing this, everything else is pointer arithmetic. rects[0] = malloc(arr2dMem); and memcpy(rects[0], arr2d, arr2dMem); copies whole arr2d to rect[0], then every next rects[i] = rects[0] + i*4; is shifted 4 integers forward. Because rect is of type int**, the expression rects[i][j] translates to *(rects[i]+j), and replacing rects[i] by rects[0] + i*4, we get *((rects[0] + 4*i)+j), that is rects[0][4*i+j]. Note striking similarity between last expression, and arr[i*4+j]. rectsColSize is somewhat superfluous in this case, but it is essential in general int** array, when every subarray could have different sizes. After wrap function is done, rects is exact copy of arr2d, but with type appropriate for your Solution structure, so we can call solutionCreate().
I need to find the length of an array, how would I do this without using the sizeof function.
eg if
Array 1 = [0 1 2 3 4 5 6]
the size of this array would be 7.
If you can't use sizeof (tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):
int arr[] = {0, 1, 2, 3, 4, 5, 6, -1};
int count = 0;
while (arr[count] != -1) count++;
Many high-level programming language save the length of an array once it is created.
/* e.g. Java */
int[] foo = new int[10];
assert(foo.length == 10);
But the length of an array is not saved in C! This is useful as you can decide how you want to save the length with respect to optimization. You basically have three possibilities to get/save the length:
mark the end of the array with a certain value (i.e. \0 is used for strings)
char foo[] = "bar";
/* foo has length 4(sic!) as '\0' is automatically added to the end*/
int i = 0;
while(foo[i] != '\0'){
printf("%c",foo[i]);
i++;
}
save the length of the array in a variable
int foo[] = {1,2,3,4};
int length = 4;
for(int i = 0; i < length;i++){
printf("%i, ",foo[i]);
}
use sizeof (warning: sizeof is (mostly) computed at compile time and its use is restricted. you can only use sizeof within the function where the array has been created. when you pass an array to a function you only pass the pointer to the first element. therefore you can loop through this array as you know what offset must be used(type of its elements), but you do not know how big it is unless you also passed the length or added a sentinel value)
/* ok */
int foo[] = {1,2,3,4};
for(int i = 0; i < sizeof(foo)/sizeof(int);i++){
printf("%i, ",foo[i]);
}
/* not ok */
void foo(int bar[]);
void foo(int bar[]){
for(int i = 0; i < sizeof(bar)/sizeof(int);i++){
printf("%i, ",bar[i]);
}
}
int main()
{
int arr[] = {1,2,3,4};
foo(arr);
return 0;
}
If this is possible:
#include <stdio.h>
#include <process.h>
#define SIZE 5
void PassingArray(int arr[])
{
int i=0;
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", arr[i]);
}
printf("\n");
}
main()
{
int myIntArray[5] = {1, 2, 3, 4, 5};
PassingArray(myIntArray);
system("PAUSE");
}
Then why the following is illegal?
#include <stdio.h>
#include <process.h>
#define SIZE 5
int ReturningArray()[]
{
int myIntArray[5] = {1, 2, 3, 4, 5};
return myIntArray;
}
main()
{
int myArray[] = ReturningArray();
system("PAUSE");
}
You're not returning an int, but you're returning the array. This is the same value as &myIntArray[0]. int ReturningArray()[] is not a valid function prototype.
There's multiple reasons why this doesn't work.
The first is simply that it's prohibited by the language - the return type of a function shall not be an array (it also can't be a function).
The second is that even if you were allowed to declare ReturningArray as you do, you could never write a valid return statement in that function - an expression with array type that is not the subject of the unary & or sizeof operators evaluates to a pointer to the first element of the array, which no longer has array type. So you can't actually make return see an array.
Thirdly, even if we somehow had a function returning an array type, you couldn't use that return value as the initialiser of an array variable - the return value would again evaluate to a pointer to the first element of the array: in this case a pointer to int, and a pointer to int isn't a suitable initialiser for an array of int.
There are several problems with this code.
You are placing the brackets at the wrong place. Instead of
int ReturningArray()[]
it should be
int* ReturningArray()
You are returning a local variable. Local variables only exist during the execution of the function and will be removed afterwards.
In order to make this work you will have to malloc the int array and return the pointer to the array:
#include <stdio.h>
#include <malloc.h>
#define SIZE 5
int* ReturningArray()
{
int *myIntArray = (int *)malloc(SIZE * sizeof(int));
myIntArray[0] = 1;
myIntArray[1] = 2;
myIntArray[2] = 3;
myIntArray[3] = 4;
myIntArray[4] = 5;
return myIntArray;
}
int main(void)
{
int i;
int* myArray = ReturningArray();
for(i=0;i<SIZE;i++) {
printf("%d\n", myArray[i]);
}
free(myArray); // free the memory again
system("PAUSE");
return 0;
}
PassingArray is legal, but it does not pass an array. It passes a pointer to the first element of an array. void PassingArray(int arr[]) is a confusing synonym for void PassingArray(int *arr). You can't pass an array by value in C.
ReturningArray is not allowed, you can't return an array by value in C either. The usual workaround is to return a struct containing an array:
typedef struct ReturnArray {
int contents[5];
} ReturnArray;
ReturnArray ReturningArray()
{
ReturnArray x = {{1, 2, 3, 4, 5}};
return x;
}
Arrays are second-class citizens in C, the fact that they can't be passed or returned by value is historically related to the fact that they can't be copied by assignment. And as far as I know, the reason for that is buried in the early development of C, long before it was standardized, when it wasn't quite decided how arrays were going to work.
You can't return array from a function, but It is possible that you can declare a function returning a (reference in C++) or pointer to array as follows:
int myIntArray[] = {1, 2, 3, 4, 5};
int (*ReturningArray())[sizeof(myIntArray)/sizeof(int)] {
return &myIntArray;
}
Greetings,
I am trying to learn pointers in C, I simply want my "addtwo" function to add 2 to every element of the input integer array, yet I get odd compilation errors, here is the non-pointer version which indeed won't properly compile.
addtwo(int *arr[]) {
int i=0;
for(;i< sizeof(arr)/sizeof(int);i++) {
arr[i] = arr[i] + 2;
}
}
main() {
int myarray[] = {1,2,3,4};
addtwo(myarray);
}
Regards
You've some problems. First, you try to pass a int* to a parameter that's type int**. That won't work. Give it type int*:
void addtwo(int *arr){
int i=0;
for(;i< sizeof(arr)/sizeof(int);i++){
arr[i] = arr[i] + 2;
}
}
Then, you need to pass the size in an additional argument. The problem is, that when you pass arrays, you really pass just a pointer (the compiler will make up a temporary pointer that points to the array's first element). So you need to keep track of the size yourself:
void addtwo(int *arr, int size){
int i=0;
for(;i<size;i++){
arr[i] = arr[i] + 2;
}
}
int main(void) {
int myarray[] = {1,2,3,4};
addtwo(myarray, sizeof myarray / sizeof myarray[0]);
}
Now it will work. Also put the return type before them. Some compilers may reject your code, since it doesn't comply to the most recent C Standard anymore, and has long been deprecated (omitting the return type was the way you coded with the old K&R C).
addtwo(int *arr[]) should be addtwo(int *arr)
You cannot use sizeof to get the size of an array from a pointer. Typically you would either pass the size of the array as a separate arg or have some special value marking the last element.
Not to do with the compile error, but...
You have to pass sizeof(arr) to the function instead of calling it in the function. When an array is passed to a function, C no longer sees it as an array, but as a single pointer to memory, so that sizeof(arr) as you are calling it now, will return the size of the pointer arr, which is most likely 4.
Here's what I mean in code:
void addtwo(int *arr, int size){
int i=0;
for(;i< size;i++){
arr[i] = arr[i] + 2;
}
}
int main(){
int myarray[] = {1,2,3,4};
addtwo(myarray, sizeof(arr)/sizeof(int));
return 0;
}
In C a notation int *arr[] is the same as int** arr.
You need to pass a pointer to the first element of the array and the array size. Array types decay to pointers in the context of function parameters. Try:
void addtwo(int *arr, size_t size){
for(size_t i = 0; i < size; i++){
arr[i] = arr[i] + 2;
}
}
int main() {
int v[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
addtwo(v, sizeof v / sizeof v[ 0 ]);
return 0;
}
Though others already gave the correct response, basically you have an array of pointers when you have
int *arr[]
I doubt that is what you want. If you have
int arr[]
then that will also be equivalent to
int *arr
addtwo argument declaration really reads:
arr is an array of pointers to integer
when you probably really want
a pointer to an array of integers
"How to Read C Declarations" has really helped me to grok the topic a while ago, maybe it will do the same for you.