warning - assignment makes pointer from integer without a cast [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
i got this warning " assignment makes pointer from integer without a cast "
(MARKED IN CODE PIECE) the code works fine, what i'm doing wrong and how can i fix this warning? thanx
void Read_Keys(char *keys[MAX_LEN]) //Read the keys from input file
{
char c,Fname[MAX_LEN];
gets(Fname);
FILE *fptr = (fopen(Fname, "r")); // Input stream pointer assume
if(fptr == NULL)
{
printf("No Such File...");
exit(EXIT_FAILURE);
}
if(fptr) //if not empty get in
{
int i = 0;
while((c = getc(fptr)) != EOF) //while loop copies each char from file
{ //to keys array
** keys[i] = c; // ** WARNING IS HERE
i++;
}
keys[i+1] = END; //ending point assume
}
fclose(fptr); //Close file for security issues
} ```

The parameter keys is declared like
char *keys[MAX_LEN]
the compiler adjusts it to the following declaration
char **keys
So in this statement
keys[i] = c;
the left operand has the type char * that is it is a pointer while the right operand has the type char.
So the compiler issues a warning because this assignment does not make sense.
I suspect that in any case the parameter is declared incorrectly. It seems you mean the following declaration
void Read_Keys(char ( *keys )[MAX_LEN]);
that is you are trying to pass a two dimensional array to the function. But in any case this code snippet
int i = 0;
while((c = getc(fptr)) != EOF) //while loop copies each char from file
{ //to keys array
keys[i] = c; // ** WARNING IS HERE
i++;
}
keys[i+1] = END; //ending point assume
}
is invalid because it trues to write all the file in one record instead of an array of records.

You keys parameter is an array of MAX_LEN pointers to char. So, if you want to assign a value inside this array, it should be a pointer to a character type. Here, getc() returns a character, not a pointer.
I think what you expect is void Read_Keys(char *keys), with the following calling code:
char keys[MAX_LEN];
Read_Keys(keys);
Thus, your keys array is decayed into a char * pointer when Read_Keys is called. Inside Read_Keys, you can access all your array elements using an index, like keys[2].
Obviously, you also need to pass you array length to Read_Keys, so the function knows which array index is valid and which one is not.

Related

Removing unused variable causes crash [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an unused variable in my function. If I remove it, the program crashes. I'm having trouble understanding why. I assume its because I'm accessing out of bounds for dataArr.
For definitions:
userFile is an argv input text file to be read
dataArr is the lines of that text file, stored into a string array.
n[80] was a previously used array of pointers that stored individual values (wrote it into a different function)
strdup duplicates the string (non-standard library)
If it helps, switching the value of n[80] to n[20] gives errors, but n[21] does not.
char ** read_file(char * userFile)
{
char * n[80]; // DO NOT REMOVE THIS LINE UNDER ANY CIRCUMSTANCES. IT IS BLACK VOODOO MAGIC.
char currLine[256];
char * dataArr[80];
char * eof;
int lineCount = 0;
int i = 0;
int j = 0;
FILE * fp;
fp = fopen(userFile, "r");
while((eof = fgets(currLine, sizeof(currLine), fp)) != NULL)
/* Stores the file into an array */
{
if (fp == NULL)
{
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
dataArr[i] = strdup(eof);
i++;
}
return dataArr;
}
EDIT:
I call the function using
dataArr = read_file(argv[1]);
I have a bad habit of using the same variable name for functions.
This happens because the array allocates memory and modifies the way your program is stored.
You cause Undefined Behavior when you do:
return dataArr;
since this array is a local variable:
char * dataArr[80];
thus it will go out of scope when the function terminates. That means that when the caller tries to use it, it will be most likely have gone out of scope.
By the way, you first read the file and then check if it opened. You should it like this instead:
fp = fopen(userFile, "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
while((eof = fgets(currLine, sizeof(currLine), fp)) != NULL) {
...
This line:
return dataArr;
will cause undefined behaviour which is among the worst problems you can face. The reason why this is so bad is that very often it is hard to pinpoint. UD very often manifests itself in strange ways like this.
This has absolutely nothing to do with char * n[80] at all.
In short, UD means that anything can happen. See this link for more info: Undefined, unspecified and implementation-defined behavior

Passing Struct * by reference C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
+I'm trying to pass from the main an array of CustomStruct by reference, but im doing something wrong:
I think i'm asking correctly for memory, but it doesn't seem so, because when i try to force some values, i get core dumped and i absolutely don't know why.
void readFile(OwnStruct **restaurant){
FILE *f;
int numTaules = 0;
f = fopen("hello.txt", "r");
if(f == NULL){
printf("Error at opening!\n");
exit(0);
}
fscanf(f,"%d",&numTaules);
//Asking for memory
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
//From here, at some point: Core Dumped
restaurant[0]->ocupades = 1;
restaurant[0]->disponibles = 2;
restaurant[1]->ocupades = 3;
restaurant[1]->disponibles = 4;
printf("%d\n",restaurant[0]->ocupades);
printf("%d\n",restaurant[0]->disponibles);
printf("%d\n",restaurant[1]->ocupades);
printf("%d\n",restaurant[1]->disponibles);
}
int main(){
typedef struct(){
int ocupades;
int disponibles;
}
OwnStruct *restaurant;
readFile(&restaurant);
return 0;
}
You are referencing the array wrong:
So far so good:
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
This is wrong:
restaurant[0]->ocupades = 1;
It should be:
(*restaurant)[0].ocupades = 1;
You must dereference the pointer to your pointer. That expression then points to the first element of the allocated array. The parentheses are needed, because postfix operators like EXPR[0] take precedence over unary operators like *EXPR, so *EXPR[0] is treated as *(EXPR[0]).
Suggestion: Work with a local pointer which is just Ownstruct *ptr. Then, just before returning from the function, store that pointer:
*restaurant = ptr;
Then you can just have ptr[0]->field = value type code in your function.
Your problem is that your function
void readFile(char fileName[], OwnStruct **restaurant)
expects two parameter, but you pass just one.
readFile(&restaurant);
Just write
readFile("myFile.txt", &restaurant);
or define your function as
void readFile(OwnStruct **restaurant)
The example you give should not currently compile - readFile expects a filename and a pointer to a pointer of OwnStruct. Your main is just providing the pointer.
The struct should defined somewhere at the top (before its use in main and readFile)
readFile is also reading numTauls from a file but then assuming it is at least 2 when assigning values to the allocated memory.

Whole file not read [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 7 years ago.
Improve this question
I have a file which contains a set of numbers.
I'm trying to read those numbers into an array. I'm allocating memory for that array using a pointer and reading from the file into the location.
For some reason, the program does not read beyond 5 values from the file.
int main(int argc, char* argv[] )
{
int i=0, count=0;
//unsigned long int num[1000];
unsigned long int *ptr;
ptr = (unsigned long int*) malloc (sizeof(unsigned long int));
char file1[30], file2[30];
int bin[1000][32];
int ch;
argv++;
strcpy(file1,*argv);
FILE *fp;
fp=fopen(file1, "r");
while((fscanf(fp,"%ld",ptr))==1)
{
ptr++;
count++;
}
ptr=ptr-count;
for(i=0; i<count;i++,ptr++)
printf("%ld\n",*ptr);
return 0;
}
The input file contains the following:
1206215586
3241580200
3270055958
2720116784
3423335924
1851806274
204254658
2047265792
19088743
The output is just this:
1206215586
3241580200
3270055958
2720116784
3423335924
Thanks in advance.
You need to allocate enough space to store your integers in. To do this , use the realloc function on the original pointer.
The fact that you write ptr++ makes it awkward to call realloc on the original pointer and save the result. So it would be a better idea to not use ptr++. Instead you can use ptr[count] and leave ptr always pointing to the start of the allocation.
For example the main loop could be:
while((fscanf(fp,"%lu",&ptr[count]))==1)
{
count++;
void *new = realloc(ptr, (count+1) * sizeof(*ptr));
if ( !new )
break; // maybe print error message, etc.
ptr = new;
}
// don't do this any more
// ptr=ptr-count;

Error when passing a 2-dim array as function's parameter in C [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 8 years ago.
Improve this question
I try to pass a two dimensional array as a parameter to a function like this:
void comb(int n, int array[n][n-1])
{
.....
}
And in the main function:
int main(int argc, const char * argv[])
{
const int p = 10;
int array[p][p-1];
comb(p, array); //Error:No matching function for call to 'comb'
return 0;
}
The "comb" function is declared above the main function. But Xcode gives me the error message on line "comb(p, array)" that "No matching function for call to 'comb' ".
I don't know how I could fix this. Also, is there some better way to pass a 2-dim array as parameter?
Your code is correct in C99.
If you get a compiler error, it could be because you are not showing the real code, or you are not invoking your compiler in C99 mode.
In C11 it is optional whether the compiler supports VLA, but your compiler documentation should indicate whether or not it is supported.
There is no other way to pass a VLA as parameter.
If your array dimension is known at compile-time then you can replace const int p = 10; with #define ARRAY_DIM 10 ; then your array will no longer be a VLA and the function can simply be:
void comb(int array[ARRAY_DIM][ARRAY_DIM-1])
{
Never passed a matrix, but when you pass arrays, the name is just the pointer to the first element.
char myArray[10];
where myArray is really a char pointer rather than a char.
You need to change something. Passing big things in functions is asking for a pointer
If comb take an array
void comb(int n, int array[n])
this should be put like
void comb(int n, int*array)
And then access to elements are in the fashion
*(array+k) ... // equals to array[k]
YOU CANNOT DO THIS
array[k] ... // Erro.
And call comb in main just in the way you did, since array names are already pointers
Not sure for bidimentional but almost sure the same, since bidim are just a big unidimensional array arranged in another way.
When passing pointer, function forget about boundaries.
Good practice is to help the function avoid disasters passing the max len
void comb(int n, int*array,int len)
{
int k=0;
While(*(array+k) !=n) // Search array for a number equal to "n".....
{
k++;
if(k>len)
return 0; // Avoid seeking outside the array, cut now. nice plase to return 0 (not found)
}
return 1; // got a hit before reaching the end.
}
Meanwhile in the main call:
comb(p, array, sizeof(array)/sizeof(array[0]); // third param is the number of elements

LValue required - Reason and solution for my first program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I am doing my 1st year engineering.
I am beginner to programming.
I have program where I get the error - LValue required on the lines - 30,31 and 32 (marked in the code below).
What is the reason for the error?
#include<stdio.h>
#include<conio.h>
struct employee
{
char empname[30];
int leave;
};
main()
{
struct employee a[1000];
int bp=5000,salary,x,i,j,k;
char w[30];
int t;
x=(bp*120)/100;
salary=bp+x;
printf("Enter the number of employees:");
scanf("%d",&j);
for(i=0;i<j;i++)
{
printf("Enter employee name and number of days he/she took leave:");
scanf("%s%d",&a[i].empname, &a[i].leave);
}
for(i=0;i<j;i++)
{
for(k=i+1;k<j;k++)
{
if(a[i].empname[0]>a[k].empname[0])
{
w= a[i].empname; // Line 30
a[i].empname=a[k].empname; // Line 31
a[k].empname=w; // Line 32
t=a[i].leave;
a[i].leave=a[k].leave;
a[k].leave=t;
}
}
}
for(i=0;i<j;j++)
{
if(a[i].leave>10)
salary=salary-((a[i].leave-10)*366);
}
for(i=0;i<j;i++)
{
printf("Employee name = %s\nNumber of days leave = %d\nSalary = %d\n",a[i].empname,a[i].leave,salary);
}
getch();
}
It looks like you want to make string copy for permutation in these lines
w= a[i].empname;
a[i].empname=a[k].empname;
a[k].empname=w;
you can not make string copy in this way in C
you have to use strcpy() instead
char * strcpy ( char * destination, const char * source );
so you can make the permutation in this way
strcpy(w, a[i].empname);
strcpy(a[i].empname, a[k].empname);
strcpy(a[k].empname, w);
Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and its value will be the address of the first element in the array. This converted expression is not an lvalue, meaning it may not be the target of an assignment.
If you want to copy the contents of one array to another, you'll need to use a library function. For C strings (arrays of char with a terminating 0 value) use strcpy or strncpy. For other array types, use memcpy.
So, those lines should be
strcpy( w, a[i].empname );
strcpy( a[i].empname, a[k].empname );
strcpy( a[k].empname, a[i].empname );

Resources