#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);
Related
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;
}
}
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.
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);
}
I am trying to initialize an array of elements to a finite value in a c function.
one way i know is to use a for loop to initialize those values but I am wondering if there is a simple way? I know that they can be initialized during array declaration though but I wouldn't prefer that way.
ex:
int a[10];
void foo(void)
{
for (int i=0; i<10;i++)
{
a[i] = 10;
}
}
Thanks
For the special case, that it is an char/byte array you could use the memset function:
#include <string.h>
void * memset ( void * ptr, int value, size_t num );
Attention: Thoug an 'int' is passed to memset, the ptr will increase in char/byte steps. So it is not suitable for an int array!
But you could use memfill:
#include <publib.h>
void *memfill(void *buf, size_t size, const void *pat, size_t patsize);
See http://manpages.ubuntu.com/manpages/saucy/man3/memfill.3pub.html for details. But it is probably not everywhere available.
I have an array/pointer related problem.
I created an int array myArray of size 3. Using a function I want to fill this array.
So I'm calling this function giving her the adress &myArray of the array.
Is the syntax correct for the function declaration`? I'm handing over the pointer to the array, so the function can fill the array elements one by one.
But somehow my array is not filled with the correct values.
In Java I could just give an array to a method and have an array returned.
Any help is appreciated! Thanks!
#include <stdio.h>
int myArray[3];
void getSmth(int *anArray[]);
int main(void)
{
getSmth(&myArray);
}
void getSmth(int *anArray[])
{
for(i=0...)
{
*anArray[i] = tmpVal[i];
}
}
Remove one level of indirection:
#include <stdio.h>
int myArray[3];
void getSmth(int anArray[]);
int main(void)
{
getSmth(myArray);
}
void getSmth(int anArray[])
{
for(i=0...)
{
anArray[i] = tmpVal[i];
}
}
Also, as others have suggested, it would be a good idea to pass the size of the array into getSmth().
No, the syntax is not correct. You have an extra *, making the argument into an array of pointers.
In general, it's better to use:
void getSmth(int *array, size_t length);
since then the function can work on data from more sources, and the length becomes available which is very handy for iterating over the data as you seem to want to be doing.
You'd then call it like so:
int main(void)
{
int a[12], b[53];
getSmth(a, sizeof a / sizeof a[0]);
getSmth(b, sizeof b / sizeof b[0]);
}
Note the use of sizeof to compute (at compile-time) the number of elements. This is better than repeating the numbers from the definitions of the variables.
Right now, your function accepts an int *anArray[] parameter, which is an array of pointers to int. Remove the unneccessary * and your function signature should look simply like this:
void getSmth(int anArray[]); // array of int
or
void getSmth(int *anArray); // pointer to first array element of type int
You should use either int anArray[] or int *anArray (which is effectively the same, because array decays to pointer). You should also make sure that the function knows how big your array is either by agreement or passing it as a parameter for it can not use sizeof for the purpose.