How to pass a array of strings to a function? - c

In the following program i just try to copy some string to the array and print it in another function.
I am getting segmentation fault .Could someone point out what i did wrong ?
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 20
void print_str(char str[][],int count);
int main()
{
char str[2][MAX_STR_LEN];
strncpy(str[0],"hello",MAX_STR_LEN);
strncpy(str[1],"world",MAX_STR_LEN);
print_str(str,2);
return 0;
}
void print_str(char str[][],int count)
{
int i;
for(i=0;i<count;i++)
printf("%s\n",str[i]);
}

We need to specify the column size mandatory when passing a 2D array as a parameter.
So, You should declare your function like this:
void print_str(char str[][MAX_STR_LEN],int count);

Use
void print_str(char str[][MAX_STR_LEN], int count);

Provide the second dimension length in a 2-D array in C always. First dimension length is optional if you are declaring a 2-D array.

Related

C - function (Assume that a and n are parameters where a is an array of int values and n is the length of the array.)

I'm new to programming and I don't really understand this question. Can some of you give me examples of what it means. How do I write a function where a is int values and n is the length?
I'm confused...
I'm not sure what your question is, as you haven't provided much information. However, a function in C is defined like this:
return_type function_name( parameter list ) {
body of the function
}
So, for this situation, we could say:
void arrayFunction( int a[], int n){
//do whatever you need to do with the function here
}
This may help you some.
Suppose you have an array of ints, as follows:
int arr[] = {2,3,4,5,6};
You can see that there are 5 elements inside above array arr. You can count them.
But it happens that when you pass the above arr to function, that function has no idea about how many elements arr contains. See below (incorrect) code snippet:
#include <stdio.h>
void display(int arr[]){
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr);
return 0;
}
The function named 'display()' has no idea about how many elements arr has
Therefore you you need to pass the extra argument (the extra argument called 'n') to tell that called function about the number of elements inside arr. You need to tell this separately - the length of arr.
Now this becomes - as you said in your question - arr is int values and n is the length
Below is the correct code:
#include <stdio.h>
void display(int a[], int n){
//Now display knows about lenth of elemnts in array 'a'
// Length is 5 in this case
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr, 5);
return 0;
}
Now, the function named 'display()' knows the length of array of int. This is the way you write code where you specify your array and its length.
More formally, this is because while passing array, it decays to a pointer and so the need arises to pass its length also alongwith it.

How to call a function to print a 2D const char* array in C?

I would like to be able to call a function with a 2D array named using const char*. In my program, I open up a CSV input, read the number of lines, create a 2D array of the appropriate size (copy over the data from the file-this step is not in the code for the sake of the question) and then want to print it (not in the main function though, to cut down on number of lines).
For this example we can ignore the CSV component so I've added a sample array just to try it out.
I know I'm getting lost in the pointers somewhere in the hand-off of the array between main() and show() since I'm getting the error "subscripted value is neither array nor pointer nor vector." I just don't know how to fix it. Any pointers on how to remedy this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define col 4
void show(const char* A){
int i, j;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(A[i][j])
printf("%s\t", A[i][j]);
else
printf("%s\t", "NULL");
}
printf("\n");
}
}
int main () {
FILE* t1count = fopen("input/t1_input.csv", "r");
t1row = countlines(t1count); // Where countlines is another function I have written but not relevant in this case
const char *strings[t1row][col]; //For this example we can use: = {{"4001","CA52","C14M731345","5"},{"4010","CA52","C14M731559","5"},{"4101","CA52","C14M731559","5"},{"4029","CA72","B15M731038","9"}};
show(strings);
}
Thanks!
There is type mismatch between your function parameter void show(const char* A) and the argument you are passing while calling show(strings);
change your function prototype to
void show(const char* A[][col])

Change Array without returning it [C]

I just have a basic question concerning arrays in functions.
I am trying to change an array in a function without returning it.
I know how to do this for integers or doubles but i didn't know how to do this for arrays. So i experimented a little bit and now I am confused.
I have 2 variations of my code which i thought should do the same thing , but they don't. I pass the array b to the function Test. In the function I try to fill the array with the values 0, 1 ,2
#include <stdlib.h>
#include <stdio.h>
void Test(int * vector){
vector = malloc(3*sizeof(int));
int i;
for(i=0;i<3;i++){
*(vector+i)=i;
}
}
int main(){
int b[3];
Test(b);
printf("%i\n",b[0]);
printf("%i\n",b[1]);
printf("%i\n",b[2]);
return EXIT_SUCCESS;
}
This Version doesnt work, i don't get the expected result 0,1,2
This Code on the other hand does seem to work:
#include <stdlib.h>
#include <stdio.h>
void Test(int * vector){
int * b = malloc(3*sizeof(int));
int i;
for(i=0;i<3;i++){
*(b+i)=i;
*(vector+i) = *(b+i);
}
}
int main(){
int b[3];
Test(b);
printf("%i, ",b[0]);
printf("%i, ",b[1]);
printf("%i ",b[2]);
return EXIT_SUCCESS;
}
Can somebody explain to me why only the second one works?
Best Regards,
Rob
When you pass an array to a function, it decays into a pointer to the first element. That's what the function sees. But then you take the function parameter vector and overwrite it with dynamically allocated memory. Then you don't have access to the array you passed in. Additionally, you have a memory leak because you didn't free the allocated memory.
In the case of the second function you don't modify vector, so when you dereference the pointer you're changing b in main.
Also, instead of this:
*(vector+i)
Use this:
vector[i]
It's much clearer to the reader what it means.
test doesn't need to call malloc(). When you use an array as a function argument, it passes a pointer to the array. So you can simply write into vector[i] and it will modify the caller's array.
void Test(int * vector){
int i;
for(i=0;i<3;i++){
*(vector+i)=i;
}
}

C: 2d char pointer in a struct

I want to write and print some strings in a 2d array in a struct. The struct is called Router and it is in a header file, the 2d array is defined in that struct and it's called **addTab. When I try to print one line of the array using the function viewTable the program stopped working... why?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "router.h"
#define N 8
#define M 3
#define sizeMess 5
Router *createRouter(){
Router *NewRouter=(Router*)malloc(sizeof(Router));
int i;
NewRouter->addTab=(char **) malloc(N*sizeof(char *));
for(i=0;i<N;i++)
NewRouter->addTab[i]=(char *) malloc(M*sizeof(char));
return NewRouter;
}
void viewTable(Router *r, int a){
int i,j;
for(i=0;i<N;i++){
for(j=0;j<M;j++){
printf("raw\t col\t address\t value\t\n");
printf("%d\t %d\t",i,j);
printf("%p\t",&r->addTab[i][j]);
printf("%s\t\n",r->addTab[i][j]);
}
}
}
void updateTable(Router *r, int conn, char *addr1, char *addr2){
r->addTab[conn][1]=addr1;
r->addTab[conn][2]=addr2;
}
First off: Don't cast the result of malloc.
Assuming that you want to store char* pointers in your 2D array (as the title of your question says), you will need to define it as char *** in your Router structure, like this:
typedef struct router {
char ***addTab;
} Router;
Next, you will need to change your createRouter function, so that it can store an array of char* pointers, instead of a single byte for each element, like so:
Router *createRouter(){
Router *NewRouter=malloc(sizeof(Router));
int i;
NewRouter->addTab=malloc(N*sizeof(char **));
for (i=0;i<N;i++)
NewRouter->addTab[i]=malloc(M*sizeof(char *));
return NewRouter;
}
I'm not sure how you call your updateTable function, but unless you actually fill up the entire array with char* pointers, your viewTable function will also invoke Undefined Behavior, because the printf statements will attempt to access uninitialized data. You could avoid this by using calloc instead of malloc when allocating the 2D array (or explicitly memset it), and then adding NULL checks in your viewTable function.
Finally, if you're calling updateTable with char* pointers that are not string literals or they have not been allocated on the heap, you might have further issues...
Your updateTable() doesn't work as you'd expect. You allocated memory in r->addTab[i][j] and, afterwards, assign a pointer to it (r->addTab[conn][1]=addr1). On access in viewTable, the program tries to read the memory at addr1, but most likely won't be able to read it, thus crashes.
Use a function to copy a given string to r->addTab, e.g. like so:
void router_tab_printf(Router *r, const int conn, const int i, const char *value) {
sprintf(r->addTab[conn][i], "%s", value);
}
This assumes that r->addTab[conn][i] is large enough to hold value.
you need to change your updateTable
void updateTable(Router *r, int conn, char *addr1, char *addr2){
strcpy(r->addTab[conn], addr1);
strcpy(r->addTab[conn+1 /*or something*/], addr2);
}

dynamically sized array in C using a function

#include <stdio.h>
#include <stdlib.h>
void dim(int*,int);
int main()
{
int *array ;
int n,i;
scanf("%d",&n);
dim(array,n);
for(i=0;i<n;i++)
scanf("%d",&array[i]);
for(i=0;i<n;i++)
printf("%2d",array[i]);
}
void dim(int *array,int n){
array=malloc(n* sizeof(int));
}
why this don't work? i can't do this?
I can't give a dimension to an array through a function?
I tried to find on Internet how this works, but i dint find anything so i prefer to post it here for a direct answer.
Thanks! and sorry for my English.
The array in the function is passed by value, what you allocated in dim doesn't affect the array in main, it's memory leak.
Instead, pass a pointer to pointer:
void dim(int **array,int n){
*array=malloc(n* sizeof(int));
}
And call it like:
dim(&array,n);
You're passing a pointer by value so dim isn't doing anything to it. You need to pass a pointer to a pointer into your function like so:
void dim(int **array, int n) {
*array=malloc(n * sizeof(int));
}
then pass in your array like so:
dim(&array, n);

Resources