How to calculate no of rows in 2D array using C [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
if the given function is as exp:then how to calculate no of rows in the given 2d array input2
void fun(char *input2[])
{
//calculate no of rows and in each row no of column
}

In general no. In C, it's not possible to calculate the size of an array using only a pointer to it.
However, if you're given a limitation, that the array is terminated by zero(^), then you can count the number of values before the zero using a loop. If it is an array of pointers (such as you have), then the terminator could be a pointer to a specific value. For example, a pointer to zero(^).
Without that limitation, you must store the length in a variable.
(^) you may use any specific value, but zero is a good choice for pointers and characterstrings.

In C, array parameters decay into simple pointers, so you have to design your function to also accept the length of the array:
void fun(char *input2[], int input2Len);
If you also define an array length macro you can call fun like this:
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
char *strings[10];
...
fun(strings, LEN(strings));

it is impossible to know the size of an array passed to function as argument, in form of type function(type array[]), that because array is a pointer to the first element of it. but there is no information about the last element.
to get over this issue. there are many solutions that we can implement. some of them may alter the implementation of the function itself as passing the size of the array in a second parameter. but if we want to keep function definition untouched. leaves to two possibilities:
1) setting the number of elements on the first item;
2) marking the end of the array (usually is an empty item)
it is almost the second one which is most adopted, here is the code to illustrate that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int mySizeOfArray(char *input[]){
char **p=input; //p point to the first element of array
while(*p){
p++;//int crementing the pointer
}
return p-input;//return the difference between them
}
/*__________________________________________________________
*/
int main(){
char *input2[]={"First","Second","Third",/*Last*/NULL};
printf("Size of input=%d\n",mySizeOfArray(input2));
return 0;
}

Related

Sort array values and store into another array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I am aiming to sort an array and then store these values once sorted inside another array. However, my for-loop continues on infinitely long until I signal the console to stop the function.
For example:
#include <stdlib.h>
#include <stdio.h>
//Sort the array from largest to smallest and store
//it inside another array
int main(int argc, char* argv[argc+1]){
int arr[] = { 9, 6, 4, 6, 3, 2, 8, 1 };
int result[] = {};
for(int i = 0; i < malloc(sizeof(arr)); i++){
result[i] = strtod(arr[i]);
printf("%s",result);
}
return EXIT_SUCCESS;
}
Incorrect Main Defination
The declaration of the main function is incorrect.
There are two valid main declarations:
int main(void)
Or
int main(int argc, char *argv[])
where argc is the argument count, and argv is an array of character pointers.
Invalid array declaration
int result[] = {}
You declared an array of unspecified size, or 0 size.
The common C idiom to determine the size of an array is:
sizeof arr / sizeof arr[0]
Number of total bytes / number of bytes of a single element.
Incorrect use of malloc
malloc(sizeof(arr))
malloc is a library function that allows you to dynamically allocate memory from the heap. That is not what you want to do.
Incorrect use of strtod
strtod(arr[i])
strtod stands for string to double, why are you trying to convert integers stored in an array that are not strings to double?
Incorrect format specifier
printf("%s", result);
result is an integer array, not a string. Why are you specifying a %s for integers? Not that a %d would correct it.
You said you're trying to sort the array. Did you try thinking of an algorithm for it? Did you research anything? I'd advise you to start all over again and pick up a good C book. There are too many problem in this code, it's not salvageable.

Is it possible to extract the size of an array of char pointers in C [duplicate]

This question already has an answer here:
Number of elements in static array and dynamic array
(1 answer)
Closed 4 years ago.
I need to specify the length of an array of char pointers as an input to a function in C. I don't think it is possible to know this in C without some trick (like iterating until a certain sentinel string is found), but I'm wondering if perhaps gcc has some function that would extract this for me?
const char *names[] = {"string1","next_string","test"};
//Later in code
int n_fields = <magic>(names);
In this case I would be looking for n_fields to be 3.
My current alternative is to manually count and specify the length, but this means I need to ensure that these two values stay linked manually.
Edit regarding duplicate question: Unlike arrays of integers it was not obvious to me what the two sizeof parameters in other examples would be measuring for an array of char pointers. Specifically I thought the denominator might be measuring string length, when in reality it was measuring the size of a pointer. Pretty much every example online is for an array of ints, not char pointers.
Sure thing:
#define ARRAY_SIZE(names) (sizeof(names)/sizeof((names)[0]))
#include <stdio.h>
const char *names[] = {"string1","next_string","test"};
//Later in code
int n_fields = ARRAY_SIZE(names);
int main()
{
printf("%d\n", n_fields); //prints 3
}
Keep in mind that you need to make sure you're applying ARRAY_SIZE to a real array, not a pointer.
void f (const char *names[])
{
//!WRONG: names is actually a pointer here
printf("%d\n", (int)ARRAY_SIZE(names));
}
To protect yourself, you can beef up ARRAY_SIZE with some gcc/clang/tcc extensions so that the erroneous code in the snippet above no longer compiles but the example with a real array continues to:
#define ARRAY_SIZE(X) ( 0*sizeof(char [ \
__builtin_types_compatible_p(__typeof(X),__typeof((X)+0)) ?-1:1 ] ) \
+sizeof(X)/sizeof((X)[0]) )
Once the array decays to a pointer, the original size can no longer be recovered through standards means, which is why functions taking array parameters (really pointer parameters) where the array isn't terminated with a sentinel usually also accept an array size parameter.

Easy way to deal with free in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When I have a function that gets a pointer int *vector with a couple int values. I want to delete element number n. So I will use free() on that element. The problem I have now that there is a "hole" in my array of int values. Is there an easy way that I dont have this problem or do I really have to make a new int pinter and reorder my vector?
Given a function of this form:
void delete_element(int *vector, size_t index) {
// ...
}
The actual argument corresponding to vector is expected to be a pointer to a series of one or more (implied: index + 1 or more) contiguous ints. This could be part or all of an ordinary int array, or it could be a dynamically allocated block. If the former, then you cannot free any part of the space at all. If the latter, then you can free or reallocate the whole space, but not just the part associated with one element.
To avoid the deletion leaving a hole in your array, you need to move the later elements down, and to do that, you need to know how many elements there are in total. Therefore, you need a more informative function signature, perhaps something like this:
void delete_element(int *vector, size_t *size, size_t index) {
// ...
}
The actual deletion might involve simply using memmove() to move the later elements (overwriting the one to be deleted), and then decrementing the size. With respect to the latter, note that I suggest passing a pointer to the vector size, so that the function can modify the caller's copy.
If you want also to shrink the allocation then you need to do a bit more work (involving calling realloc(), and communicating the revised value of vector back to the caller), but note that in that case your function will not work on ordinary arrays.
There is no way to free() part of a block returned by malloc(). If you want to delete record[n], you need to copy record[n+1]...record[last] into the array.
If you really need to free() each element, you must first malloc() each element.

how does compiler gets correct string without a receiver array from function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
my program
#include<stdio.h>
#include<conio.h>
char* mystrcat(char* , char* );\\ function declared as global
main()
{
char dest[50]="hello"; \\destination string
char src[50]="readers"; \\source string
clrscr();
mystrcat(dest,src);\\function calling but does not have receiving array
puts("after concatenation"); \\ of strings
puts(dest);\\shows "helloreaders"<-- how?
getch();
return 0;
}
char* mystrcat(char* des, char *sr)\\for concatenating two strings
{
int i=0,j=0;
while(des[i]!='\0')
{ i++;}
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
puts(sr);\\"readers"
puts(des);\\"helloreaders"
return sr;\\returning source string
}
output:
readers
helloreaders
after concatenating:
helloreaders
I am returning only source string from mystrcat(). But how compiler knows the modified destination string? Since I declare the function globally the compiler knows the modified string?
It is not because of return sr, rather it is because char* mystrcat(char* des, char *sr) modified its argument ( des ). Even if you change the return value to just an int, the result will be same. The reason is when you pass a char[] variable to a function, you just pass a pointer, anything you did inside the function to the variable will be reflected to the caller.
When you called function
mystrcat(dest,src);\\function calling but does not have receiving array
you passed as arguments two arrays that are implicitly converted to pointers to first elements of each array.
So inside the function you deal with addresses of the memory extents occupied by the arrays. And you write in the memory occupied by the destination array elements of the source array
while(sr[j]!='\0')
{
des[i]=sr[j];
i++;j++;
}
des[i]='\0';
because des and sr hold addresses of first elements of the arrays.
So the memory occupied by array dest was overwritten.
You are giving mystrcat() a pointer to dest and when it writes through that pointer, it changes dest directly. It doesn't matter what the function returns. des[] in mystrcat() is not a copy of dest[] in the main program, it's the same thing.
because parameters you pass to the function are points,arrays they point to are changed, but these points are not changed

Why "sizeof()" of a table isn't correct when table is a parameter of the function? [duplicate]

This question already has answers here:
What is array to pointer decay?
(11 answers)
Closed 9 years ago.
Two simple examples:
Size will be correct value when:
int table1[] = "datadata";
int size1 = (sizeof(table1) / sizeof(*(table1))) - 1;
Size won't be correct when:
int main(void)
{
...
send("datadata");
...
}
void data(int table2[]) {
int size2 = (sizeof(table2) / sizeof(*(table2))) - 1;
}
size2 will always be size of 3. Why is that? How to get correct values?
Whenever you pass an array to a function, it "decays" to a pointer. That is, void data(int table2[]) is equivalent to void data(int* table2).
If you want to pass an array to a function, use a separate argument for the length, like this:
void data(int table2[], int length)
This is what C itself does with the argc parameter to the main() function.
In the first case, the compiler is aware of the size of table and of its type (constant). Therefore, it is able to calculate the size of the char array.
In the second one, the function only receives the array's address.
Think of the scenario where I'll tell you: "There is an array of integers at 0x00F25255, I need you to sum its values". You definitely can't, because you don't know how far it goes.
To solve this issue, simply add another parameter which will represent the length of the array.
One example is main which definition may be int main(int argc, char *argv[]), where args is the count of the arguments sent.
Because the function is getting the address of the integer array, equivalent to a pointer. And in your platform pointers are 4 bytes long.

Resources