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;
Related
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 2 years ago.
Improve this question
What is the best way to write a function to return an array of String.
I use the following function:
void getOperatorNames(char *names[]) {
int i=0;
for(; i<MAX_OPERATORS; i++) {
names[i] = malloc(64 * sizeof(char));
strcpy(names[i], op[i].fname);
}
}
and call it :
char *MenuItems[MAX_OPERATORS];
getOperatorNames(MenuItems);
But when I use MenuItems in a function with argument char ** it rises an exception and I don't know what is the cause.
What is the difference between char *x[] and char **x? IMO they must be equal!!
EDITTED:
struct operator{
int id;
char fname[32];
char ename[32];
};
struct operator op[MAX_OPERATORS];
the operators is filled by random text.
One way is to pack the array and its size together in a super-struct, and avoid the nasty-sized functions arguments:
#include <stdio.h>
#include <stdlib.h>
#define MAX_OPERATORS 666
struct operators {
unsigned count;
struct operator{
int id;
char fname[32];
char ename[32];
} ops[MAX_OPERATORS];
} ;
struct operators * getops(void)
{
struct operators *ret;
unsigned uu;
ret = malloc (sizeof *ret);
if (!ret) return ret;
ret->count = MAX_OPERATORS;
for(uu=0; uu < ret->count; uu++) {
ret->ops[uu].id= uu;
sprintf(ret->ops[uu].fname, "f%2u", uu);
sprintf(ret->ops[uu].ename, "e%2u", uu);
}
return ret;
}
This is only the beginning, you can lateron make the array variable-sized (using malloc, or a VLA), but the interface would stay the same, and the caller would not need to know the value of MAX_OPERATORS, it only needs the ->count structure element. You could also reuse it for other tables, using different counts.
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 2 years ago.
Improve this question
I am trying to debug a text editor program where I create a 2D array that doubles its size every time there's a new input from a file. Valgrind returns this:
==1454== Process terminating with default action of signal 6 (SIGABRT)
==1454== at 0x48A518B: raise (raise.c:51)
==1454== by 0x4884858: abort (abort.c:79)
==1454== by 0x48EF3ED: __libc_message (libc_fatal.c:155)
==1454== by 0x49919B9: __fortify_fail (fortify_fail.c:26)
==1454== by 0x4991985: __stack_chk_fail (stack_chk_fail.c:24)
==1454== by 0x10980C: main (in /home/utente/Desktop/main)
here's my main where I call a fun to reallocate the array
int main() {
FILE *fp;
cmd istruction;
char **Array = {0};
fp=fopen("prova.txt", "rt");
int dim=30;
Array = Create2D(H);
istruction=GetOrder(fp);
while (dim<variable) {
Array = Reallocation2D(Array,dim);
dim=dim*2;
}
doing stuff...
}
}
free2D(Array, dim);
fclose(fp);
}
the create array and reallocation2D are
char ** Create2D(ssize_t Strings)
{
char **a = {0};
a = calloc(Strings, sizeof(char *));
return a;
}
char ** Reallocation2D(char ** a, size_t dim){
int i;
char **b = {0};
b = calloc(dim*2, sizeof(char *));
for(i=0;i<dim*2; i++)
{
b[i] = calloc(1024, 1);
}
for(i=0;i<dim;i++){
if(a[i]) strcpy(b[i],a[i]);
}
for(i=0;i<dim; i++)
{
if(a[i]) free(a[i]);
}
free(a);
return b;
}
Without the code, one can only try and analyse valgrind's output:
The problem seems to occur in the main() function where you have a stack overflow. Do you call a function that define a very large automatic array? Or do you define such an array in main() itself?
From the posted code, here are some problems:
the initial call to Create2D allocates space for a H pointers, but you initialize dim to 30. H is not defined, is it a #define for 30?
where does variable get set?
why do you reallocate the char arrays instead of copying them?
you allocate lines with a size of 1024 bytes. This may use much more code memory than the file on disk an would still not suffice if a line in the file os longer than that.
why not use realloc() in Reallocation2D and initialize the newly allocated part to NULL pointers?
you should test for allocation failure and report it.
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.
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 4 years ago.
Improve this question
I'm trying to have this string print out individual names. Instead of printing one name at a time, it prints all the names out. Can someone show me what I'm doing wrong? Thanks in advance.
#include <stdio.h>
#define NUM_OF_NAMES 8
#define NAME_SIZE 3
void printNames(char names[][NAME_SIZE], int size);
int main()
{
char nameList[NUM_OF_NAMES][NAME_SIZE] = {"Bob",
"Sue",
"Jak",
"Rod",
"Jon",
"Ash",
"Deb",
"Kay"};
printf("\n\n\nLIST\n");
printNames(nameList, NUM_OF_NAMES);
}
void printNames(char names[][NAME_SIZE], int size)
{
for(int index = 0; index < size; index++)
{
printf("%4s\n", names[index]);
}
return;
}
The reason the program prints all names together is that the individual three-character names are not null-terminated. printf tries printing the first name, does not find null terminator, goes into the next name, then the next one, and so on. In the end, this is undefined behavior, because the eventual null termination of the whole arrays is not there.
This problem happens because NAME_SIZE is too small - it does not accommodate null terminator.
Fix this by changing NAME_SIZE:
#define NAME_SIZE 4
Enabling warnings and treating them as errors would help you avoid this problem in the future.
Firstly, in char nameList[NUM_OF_NAMES][NAME_SIZE] you have defined NAME_SIZE as 3 and you are storing exactly 3 char into that, so there is no memory space kept for '\0' null terminator, as char buffer should be null terminated. To avoid this problem increase the NAME_SIZE. for e.g
#define NAME_SIZE 4
Secondly, from main() you are passing 2D array nameList you have to catch with pointer to an array like char (*names)[NAME_SIZE] not with 2D array as you did.
Here is the modified Code
#define NUM_OF_NAMES 8
#define NAME_SIZE 4
void printNames(char (*names)[NAME_SIZE], int size) { /*catch with pointer to an array of NAME_SIZE char */
for(int index = 0; index < size; index++) {
printf("%4s\n", names[index]);
}
}
int main(void ){
char nameList[NUM_OF_NAMES][NAME_SIZE] = {"Bob",
"Sue",
"Jak",
"Rod",
"Jon",
"Ash",
"Deb",
"Kay"};
printf("\n\n\nLIST\n");
printNames(nameList, NUM_OF_NAMES);
return 0;
}
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 3 years ago.
Improve this question
Stack create(int c)
{
Stack S=(Stack)malloc(sizeof(struct stack));
S->size=c;
S->top=-1;
S->array=(char *)malloc(sizeof(char)*c);
return S;
}
Stack makeEmpty(void)
{
Stack *S1=create(100);
S1[0]->top=-1;
return S1;
}
char pop(Stack S)
{
return S->array[S->top--];
};
int main(void)
{
Stack *S1;
S1=makeEmpty();
int j;
int k=0;
char result[30];
for(j=0; j<2; j++)
{
char result1=pop(S1);
strcat(result, result1);
k++;
}
}
I skipped some parts, like typedef struct stack Stack;
What I wanted to do was pop out elements from the stack while for-loop works. Then, store those elements in a new array which is result. To check whether it works or not, I printed out but I had a runtime error. How to store the element and how to print it out?
I've made copy&paste of your code, and it doesn't get compiled. I think that
you are either not posting your actually code nor you don't bother to compile and read the compiler warnings. It's rather difficult to help you. Here some things I noticed:
1.
create must return a pointer to Stack, not the object.
Stack *create(int c)
{
Stack *S = malloc(sizeof *S);
S->size=c;
S->top=-1;
S->array = malloc(c);
return S;
}
2.
Same goes for makeEmpty
Stack *makeEmpty(void)
{
Stack *S1=create(100);
S1->top=-1;
return S1;
}
3.
pop should get a pointer to Stack, not the object
char pop(Stack *S)
{
return S->array[S->top--];
};
Here you should check whether there are elements on your stack. int pop(Stack *S, char *val) where it returns 1 and writes on *val on
success, and returns 0 otherwise would be better.
4.
Judging from your pop you are pushing char only. I don't get what you
are trying to do with strcat. Either way, you are doing strcat wrong. You
are declaring a stack with 100 spaces, but you are only declaring 30 spaces
for result. What if you have more than 31 elements on your stack? I know
that you are only inspecting 2 elements but it's easy to overlook that and
expand it to go through all the stack without changing the memory requirements
for result.
Also strcat is a function that works with C-Strings, that means it expects
C-Strings. A C-String must be \0 terminated, yours are not. You have
something that looks like a C-String but it's not. If you insist on using
strcat, the you should do it like this:
for(j=0; j<2; j++)
{
char result1[] = { pop(S1), 0 };
strcat(result, result1);
}