C program char pointer not displaying character after passing through functions - c

I would love your help in solving this as I have not found a solution in the many examples and videos I found.
I am to create a scrabble game using C programming but for some reason when I pass the character pointer through my functions, the last one to display the scrabble board does not print the letter from my previous function.
Instead of printing the randomly generated character, it prints an empty string.
I have copied the parts of the code that is involved.
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int k,j;
char * grid[8][8];
void play(int x, int y, char*c){
grid[x-1][y-1] = c;
}
void display(){
for (j=0; j<8; j++){
for (k=0; k<8; k++){
if (strcmp(grid[k][j], "")==0){
printf("%s", grid[k][j]);
}else{
printf("%s ", grid[k][j]);
}
}
}
}
void start(){
char c[2], *rc;
c[0] = rand();
rc = &c[0];
play(rand()%8, rand()%8, rc);
}
int main(int argc, char *argv[]){
play(3,7,"a");
play(4,5,"b");
start();
display();
}

Some comment :
void start(){
char c[2], *rc; // c string is local to the function
c[0] = rand();
rc = &c[0]; // rc points to a string inside the function
play(rand()%8, rand()%8, rc); // you save an address local to the function
}
When start function exits, rc value (= c address) are no more meaningful.
You should allocate memory in the function to have valid and addresses.

Related

How to return an array from function to main [duplicate]

This question already has answers here:
Returning an array using C
(8 answers)
Closed 6 years ago.
I have to use the function to open a file, read it, save the first value as the number of following elements (dimension) and the other values in the seq[] array.
I don't know how to return both dimension and seq[] in the main; I need it because I have to use these values in other functions. As the code shows, the function returns the dimension (dim), but I don't know how to return the array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int leggiSequenza(char *nomeFile, int *seq) {
FILE *in;
int i;
int dim;
if((in = fopen(nomeFile, "r"))==NULL) {
printf("Error.\n");
return -1;
}
fscanf(in, "%d", &(dim));
printf("Find %d values.\n", dim);
if(dim < 0) {
printf("Errore: negative value.\n");
return -1;
}
seq = (int*) malloc(dim*sizeof(int));
i=0;
while(!feof(in) && i<(dim)) {
fscanf(in, "%d", &seq[i]);
i++;
}
for(i=0; i<(dim); i++) {
printf("Value in position number %d: %d.\n", i+1, seq[i]);
}
free(seq);
fclose(in);
return dim;
}
int main(int argc, char* argv[]) {
int letturaFile;
char nomeFile[200];
int *dimensione;
printf("Insert file name:\n");
scanf("%s", nomeFile);
printf("\n");
letturaFile = leggiSequenza(nomeFile, dimensione);
dimensione = &letturaFile;
printf("dimension = %d\n", *dimensione);
return 0;
}
I think the focus of the problem is *seq; I have to return two values (dimension and array). Moreover, I can't edit the parameters of the function.
I think my question is different from this because in my function there is a parameter with a pointer, and the function hasn't got a pointer...
Change the function to take the array pointer by pointer:
int leggiSequenza(char *nomeFile, int **seq);
// ^^^^^^^^^
Then call it with the address of your variable:
leggiSequenza(nomeFile, &dimensione);
// ^^^^^^^^^^^
Inside the function definition, change the details around like so:
int leggiSequenza(char *nomeFile, int **seq) {
// ...
int *local_seq = malloc(dim*sizeof(int));
// use local_seq in place of seq
// free(local_seq); // delete ...
*seq = localsec; // ... and replace with this
return dim;
}
Finally, the caller needs to free the array:
free(dimensione);
Update: Since you've re-asked your question: Pre-allocate the memory at the call site:
int * p = malloc(200 * sizeof(int));
int dim = leggiSequenza(filename, p);
// ...
free(p);
Simply your function should have this signature
int leggiSequenza(char *nomeFile, int **seq)
and when passing the parameter to it you should do
letturaFile = leggiSequenza(nomeFile, &dimensione);
that way, you'll have both things.
Also, everywhere in your function where you have just seq , you need to add *seq so you can dereference the pointer.
Hope this helps!
Do the alloction of the array in the main function
int *dimensione; = (int*) malloc(200*sizeof(int));
then delete this line
free(seq);
and you should have the data in the array in the main function.

Why break gets me out of 2 loops at once and how to fix it [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 6 years ago.
Ok, so the idea of the task I have (I am the student) is to allow user to insert a string of words in this form: num1_num2_num3..._numN. The code should create an array X, give it memory dynamically and then I should fill X with numbers from string user inserted. Simple as that. Well, in the function stringuniz() I thought I had it all figured out but it simply wont work. It gets the first number well but it then stops and I think its because of the break. Break behaves (if I am right) like it breaks the entire code and not just the loop. Do you guys have an idea why is this happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringuniz(char *);
int *x;
int main(){
char s[50];
int i;
puts("Unesite string brojeva u formatu br1_br2_...brN: ");
gets(s);
stringuniz(s);
for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
}
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
x=(int*)malloc((c+1)*sizeof(int));
if(x==NULL) exit(1);
for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
}
}
}
}
This
(sizeof(x)/sizeof(int)
won't give you the size of the array. sizeof(x) is the bytesize of int* (likely 4 or 8).
You'll need to remember the size as implied by the number of _ in the string.
Also you have some off-by-one errors in there and for future reference, you might want to choose more descriptive variable names for code you decide to post publicly.
The code worked for me once I changed it to:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringuniz(char *);
int *x;
int x_size = 0;
int main(){
char s[50];
int i;
puts("Unesite string brojeva u formatu br1_br2_...brN: ");
fgets(s,50,stdin);
stringuniz(s);
for(i=0;i<x_size;i++)
printf("%d\n",x[i]);
}
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
x=malloc((c+1)*sizeof(int));
x_size = c+1;
if(x==NULL) exit(1);
for(i=0;i<=c+1;i++){
for(j=m;j<=duz;j++){
if(s[j]!='_' && s[j]!='\0'){
b[k++]=s[j];
m++;
}
else {
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
}
}
}
}
void stringuniz(char *);
int *x;
int main(){
[...]
}
void stringuniz(char *s){
[...]
}
I don't know why many ppl teach it this way, but there is absolute no use in having main somewhere in the middle of a source file, and putting it at the end also allows you to get rid of the forward declarations. So, I would write it this way:
int *x;
void stringuniz(char *s){
[...]
}
int main(){
[...]
}
Then you should start using the space character more.
stringuniz(s);
for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
In a comment, alain already pointed out, that sizeof(x) will return the size of a pointer. So, you need a different way to figure out the size of the array. One way is to add a variable size_t x_len; besides int * x;. Also, you should use curley brackets even for one line statements, believe me, not only makes it the code more readable, it also prevents introducing bugs on later changes.
for (i = 0; i < x_len; i++) {
printf("%d", x[i]);
}
.
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
b will hold the word the user enters. If his word is longer then 9 characters, you get a buffer overflow here.
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
You are counting the number of words here. So, please use more descriptive names like num_words instead of c. BTW: This is the x_len mentioned above.
x=(int*)malloc((c+1)*sizeof(int));
No need to cast return value of malloc. Actually it might hide bugs. Also, I would use sizeof(*x) instead of sizeof(int), because if you change the type of x, in your statement, you also would have to change the malloc call. In my statement, the malloc call doesn't need to be touched in any way.
x = malloc((c+1) * sizeof(*x));
if(x==NULL) exit(1);
for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
You are constantly overwriting b with the next word being read. Since you're not using it anyway, you can just skip this line.
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
And this break; only breaks out of the innermost for (j-loop.
}
}
}
}

C: Using strcpy to transfer one struct element to an array

Okay, so we're supposed to prompt a user to enter 25000 lines of text.
Each line contains three integers each. We are then to pass the third integer in that line to another struct, and connect each integer until you have 25000 interconnected integers.
Here's what I've tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct graph{
int begin;
int end;
int cost;
} PathEdge;
int comp_fcn(const void *a, const void *b) {
return ((PathEdge *) a)->cost - ((PathEdge *) b)->cost;
}
int main(void)
{
int nlines,i;
char r;
int ecost,ebegin,eend;
scanf("%d",&nlines);
PathEdge edges[nlines+1];
for(i=0;i<nlines;i++)
{
scanf("%d, %d, %dn",&ebegin, &eend, &ecost);
edges[i].begin = ebegin;
edges[i].end = eend;
edges[i].cost = ecost;
struct town
{
struct town *north;
int name[25000];
};
struct town *root, *current;
root = malloc(sizeof(struct town));
root->north = NULL;
strcpy (root->name,ecost);
current = malloc(sizeof(struct town));
current->north = root;
strcpy (current->name,ecost);
}
printf("Please enter a node that you want to examine. If you want to exit, please press 'X'.n");
scanf("%c",&r);
switch(r)
{
case 'X':
case 'x':
printf("You entered a wrong value. Gomen. Try againn.");
break;
default:
if((0<r)&&(r<25000))
{
printf("You have accessed node %dn",r);
printf("Its neighboring nodes are %dn",edges[r].cost);
printf("Its neighboring nodes are %dn",edges[i].cost);
}
else
{
printf("Invalid input again. Please do try again. Thanksn");
}
break;
}
return 0;
}
And there are warnings...
"passing argument 1 of strcpy from incompatible pointer type"
"passing argument 2 of strcpy makes pointer from integer without a cast"
expected char*__ restrict __ but argument is of type 'int'
plus when I inputted that 25000 lines of text, segmentation fault happens. Please help. Thank you!
strcpy is for copying strings (i.e. zero terminated byte char "arrays"), you maybe should use memcpy instead.
Or if you just want to assign a single integer to one element in the array, use plain assignment:
current->name[someIndex] = ecost;
Or, maybe you intend that thename member should be a string? Then you should be using an array of characters and not integers. And you need to convert integer values to strings, using e.g. sprintf:
sprintf(current->name, "%d", ecost);
you can convert the integer to string using itoa and copy the string into root->name.
char str[20];
itoa(ecost, str, 10);
strcpy(root->name, str);
You did not state your exact issue so I am assuming you are overwhelmed and in that case you should try partitioning your implementation into functions so that you can work on isolated problems instead of a web of interconnected problems.
Here is one example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct graph {
int begin;
int end;
int cost;
} PathEdge;
const char * GenerateInput()
{
static char local[2000];
static int last = 0;
int a, b, c;
a = last++;
b = last++;
c = last++;
sprintf_s(local, 2000, "%i %i %i", a, b, c);
return local;
}
void PathEdgeInitializeFromString(PathEdge * edge, const char * str)
{
sscanf_s(str, "%d %d %dn", &edge->begin, &edge->cost, &edge->end);
}
void QueryAndPrint(PathEdge * edges, int edges_n)
{
printf("Enter a number from 1 to %i: ", edges_n);
int index = 0;
scanf_s("%i", &index);
--index;
if (index < 0 || !(index < (edges_n)))
printf("Error");
else
printf("%i, %i, %i\n", edges[index].begin, edges[index].cost, edges[index].end);
}
int main() {
PathEdge edges[25000];
for (int i = 0; i < 25000; ++i)
{
const char * line = GenerateInput();
PathEdgeInitializeFromString(edges + i, line);
}
QueryAndPrint(edges, 25000);
return 0;
}

Why am I not able to access values that were stored in another function?

Basically, why does it not just print the integers that are entered. Right now it just prints garbage value, but I do not know why it cannot access the values stored after it leaves the function. It only seems to get messed up after leaving the getIntegersFromUser function. If I run the for loop in the getIntegers function it does it properly, but why not in the main function?
Thanks in advance for your help.
#include <stdio.h>
#include <stdlib.h>
void getIntegersFromUser(int N, int *userAnswers)
{
int i;
userAnswers =(int *)malloc(N*sizeof(int));
if (userAnswers)
{ printf("Please enter %d integers\n", N);
for (i=0;i<N; i++)
scanf("%d", (userAnswers+i));
}
}
int main()
{
int i, M=5;
int *p;
getIntegersFromUser(M, p);
for (i=0;i<5;i++)
printf ("%d\n", p[i]);
return 0;
}
Also, this is a homework question, but it's a "Bonus Question", so I'm not trying to "cheat" I just want to make sure I understand all the course material, but if you could still try to give a fairly thorough explanation so that I can actually learn the stuff that would be awesome.
Pointers are passed by value. The function is using a copy of your pointer, which is discarded when the function ends. The caller never sees this copy.
To fix it, you could return the pointer.
int *getIntegersFromUser(int N)
{
int *userAnswers = malloc(...);
...
return userAnswers;
}
/* caller: */
int *p = getIntegersFromUser(M);
Or you could pass your pointer by reference so the function is acting on the same pointer, not a copy.
void getIntegersFromUser(int N, int **userAnswers)
{
*userAnswers = (int *) malloc(N*sizeof(int));
...
}
/* caller: */
int *p;
getIntegersFromUser(N, &p);

Stray characters in char array

I am having a problem with this code, this code is a encryption for a rail cipher and if you enter in an input "testing" you should get an output "tietnsg" which i do get.
However if i change the input to "testingj" i get an output of "tietnjsgp?²!lj" i can see from my debugging the "?²!lj" appears to be tagged on during the last fill in the toCipher function
does anyone know how to fix it other than the way that i did it?
/*
CIS Computer Secutrity Program 1
10-10-14
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
char *toCipher(char **arr,int x,int y);
char *Encrypt(char *pT, int size);
char **create(int x,int y);
void FreeArr(char **array, int y);
void print(char *word,int strl);
int main(){
char pt[]= "testingj";
char *word = Encrypt(pt,3);
print(word, sizeof(pt));
free(word);
}
/*
Take in a pointer to a word, and the lenght of the string
Post print each char in the array, (used beacuase i had some issues with the memory, i keep getting extra adresses
*/
void print(char *word,int strl){
int i;
for(i=0;i<strl-1;i++){
printf("this is correct %c",word[i]);
}
printf("\n");
}
/*
Pre, take in the pointer to the plain text word to be encrypted as well as the depth of the Encryption desired
Post: Construct the array, insert values into the 2d array, convert the 2d array to a 1d array and return the 1d array
*/
char *Encrypt(char *word,int y){
int x = strlen(word);
int counter=0;
int ycomp=0;
int rate=1;
char **rail = create(x,y);
while(counter<x){
if(ycomp==y-1){
rate=-1;
}
if(ycomp==0){
rate=1;
}
rail[counter][ycomp]=word[counter];
ycomp=ycomp+rate;
counter++;
}//end of rail construction
char *DrWord = toCipher(rail,x,y);
FreeArr(rail,y);
return(DrWord);
}
/*
Create a dynamic 2d array of chars for the rail cypher to use
Take in the dimensions
return the pointer of the rails initial address, after it created the space for the rail
*/
char *toCipher(char **arr,int x,int y){
int xI =0;
int yI=0;
int counter =0;
char *word = (char*)malloc(x);
int i;
for(yI=0;yI<y;yI++){
for(xI=0;xI<x;xI++){
if(arr[xI][yI]!= 0){
word[counter]=arr[xI][yI];
counter++;
}
}
}
printf("this is the problem %s\n",word);
return(word);
}
char **create(int x, int y){
char **rail;
int i,j;
rail = malloc(sizeof(char**)*x);
for(i=0;i<x;i++){
rail[i]= (char*)malloc(y * sizeof(char*));
}
for(i=0;i<y;i++){
for(j=0;j<x;j++){
rail[j][i]= 0;
}
}
return(rail);
}
/*
Pre, take in a malloc'd array, with the height of the array
free the malloc calls one by one, and finally free the initial adress
*/
void FreeArr(char **array, int y){
int i;
for(i=0;i<y;i++){
free(array[i]);
}
free(array);
}
In toCipher, the word is printed without nul-termination. Either:
char *word = (char*)malloc(x+1); // allocate an extra char for nul.
word[x] = 0; // add the nul at the end.
or:
printf("this is the problem %.*s\n",x,word); // limit characters printed to x.
I forgot to initialize word to 0, the tagged memory if you watch it in debug mode was not being replaced, therefore was tagged along in the newly constructed string

Resources