String printing [closed] - c

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;
}

Related

best way to write a function to return an array of String with limited size (char *x[MAX] vs char **x)? [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 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.

Malloc in array gives Segmentation fault [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
In my attempt to understand malloc and structs I have come across an error I do not understand
#include <stdio.h>
#include <stdlib.h>
typedef struct match
{
int round;
} match;
void foo(match *matches) {
for(int i = 0; i < 10; i++) {
matches = (match *) realloc(matches, i + 1);
matches[i].round = i + 1;
}
}
int main()
{
match *matches;
matches = (match *) malloc(0);
foo(matches);
free(matches);
return(0);
}
So in my attempt to fill this array of matches dynamicaly it fails
Your foo function is very flawed. First, the parameter passes a copy of the matches pointer, so when you realloc, that updates the foo matches pointer, but not the matches pointer in main. This may cause problems with the free in main. You need to change the parameter to foo to be a double pointer: void foo(match **matches). Then to realloc, *matches = realloc(...
Next, the second parameter to realloc is a size. But i + 1 isn't going to be big enough for a full copy of the match struct. You probably meant to do something like sizeof(struct match) * (i + 1).
I addition to above answer. Good Explanation...
Please check the error from realloc as well before using the memory,
Modified the program
void foo(match **matches) {
for(int i = 0; i < 10; i++) {
*matches = realloc(*matches, (i+1) * sizeof(match));
...
}
}
int main()
{
...
foo(&matches);
...
}

Modify a string from a stucture [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 have a some problems writing a code in which I want to modify a file extension stored in a string.For example string bla/bla/file.icc i want to be changed to bla/bla/file.cmr. This string makes part from a structure. I have 2 issues. One is that strcpy gives this message "expected expression before td_ActDOR and second one is in for and give's this message subscribed value is neither array nor pointer.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s_ActDOR
{
char pDOR_file[86];
}td_ActDOR;
int main(void)
{
char path[80]="blabla/blabla/aici.icc";
td_ActDOR *Obiect;
Obiect = (td_ActDOR *)malloc(sizeof (td_ActDOR));
strcpy(td_ActDOR->pDOR_file, "blabla/blabla/file.icc");
int path_lenght=strlen(td_ActDOR->pDOR_file);
int i;
char bla[4] = "rmc\0";
printf("Stringul before: %s\n",path);
for (i = 0; i < 3; i++)
{
Obiect->pDOR_file[path_lenght-(i+1)] = bla[i];
}
printf("Stringul after: %s\n",path);
return 0;
}
In your code, td_ActDOR is not a variable, (it's a type), Obiect is.
Change
strcpy(td_ActDOR->pDOR_file, "blabla/blabla/file.icc");
to
strcpy(Obiect->pDOR_file, "blabla/blabla/file.icc");
Same goes for strlen(td_ActDOR->pDOR_file);, too.

Reading into array [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
Please help, I need to read an input txt file into an array and print it out put somehow I keep getting error message.
#include <stdio.h>
void reading_into_array(int A[]);
#define MAXVALS 100
int
main(int argc, char *argv[]){
int numbers[100], i;
reading_into_array(numbers[MAXVALS]);
for(i = 0; i < 100; i++){
printf("%d", numbers[i]);
}
return 0;
}
/*input information*/
void
reading_into_array(int A[]){
double inp;
int n = 0;
while(scanf("%lf",&inp) == 1){
A[n++] = inp;
}
}
numbers[MAXVALS] is out-of-range and its type doesn't match with the function argument. use numbers instead.
Avoid using values of uninitialized variables having automatic storage duration, which invokes undefined behavior. Initialize numbers like int numbers[100]={0},i;
When calling a function that takes an array as a parameter, you only need to supply the name of the array, e.g. numbers. "numbers[MAXVALS]" would supply the value of the MAXVALth element of this array. This is wrong for two reasons:
the function needs an array, not an element
The array has a size MAXVAL; its elements are counted from zero to MAXVAL-1, so the MAXVALth element does not even exist
If you want floating point numbers in your array, declare the array as double A[MAXVAL] everywhere.
Last note: the reading_into_array function should have a check that it will prevent it from putting more than MAXVAL numbers into the array, or you risk that it will corrupt memory and crash your program.

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;

Resources